Nic Barker
Nic Barker

Reputation: 1000

What is the purpose of the &() syntax?

I've been writing some Vulkan code using the rust library Vulkano, and came across the following snippet:

let compute_pipeline = Arc::new(ComputePipeline::new(
    device.clone(),
    &shader.main_entry_point(),
    &(),
));

I'm specifically asking about the 3rd parameter here - in the implementation of ComputePipeline::new it is listed as :

/// Builds a new `ComputePipeline`.
pub fn new<Cs>(
    device: Arc<Device>,
    shader: &Cs,
    specialization: &Cs::SpecializationConstants,
) -> Result<ComputePipeline<PipelineLayout<Cs::PipelineLayout>>, ComputePipelineCreationError>
where
    Cs::PipelineLayout: Clone,
    Cs: EntryPointAbstract,
{
    ...
}

What is the &() syntax here? A reference to the unit type?

Upvotes: 1

Views: 192

Answers (3)

Peter Hall
Peter Hall

Reputation: 58735

Yes it's a reference to a unit. This is needed here because ComputePipeline::new is generic:

pub fn new<Cs>(
    device: Arc<Device>,
    shader: &Cs,
    specialization: &Cs::SpecializationConstants
) -> Result<ComputePipeline<PipelineLayout<Cs::PipelineLayout>>, ComputePipelineCreationError> where
    Cs::PipelineLayout: Clone,
    Cs: EntryPointAbstract, 

The type of specialization is an associated type related to the type of the shader. The type of value provided for shader will determine the type of specialization, depending on its implementation of EntryPointAbstract.

In the example code you've provided, it's not clear what type shader.main_entry_point() has, but it must have an implementation of EntryPointAbstract and its associated SpecializationConstants type is ().

In order for type checking to work, you must pass &() for specialization, even though it most likely represents "no value". The compiler can optimise this away so, at runtime, this value does not exist and the function effectively has only two parameters.

Presumably, other implementations of EntryPointAbstract have more interesting types for SpecializationConstants.

Upvotes: 3

Ibraheem Ahmed
Ibraheem Ahmed

Reputation: 13528

Vulkano's ComputePipeline::new takes a reference to the associated type SpecializationConstants as its third parameter:

pub fn new<Cs>(
    device: Arc<Device>,
    shader: &Cs,
    specialization: &Cs::SpecializationConstants
)

In this case, the associated type is a zero tuple, or the unit type:

type SpecializationConstants = ()

Passing a reference to a value means adding a &, so a reference to the unit type looks like this &() :

ComputePipeline::new(
  ...
  &(),
)

Upvotes: 3

kmdreko
kmdreko

Reputation: 60052

[Is it] a reference to the unit type?

That's exactly what it is. Its just passing a reference & to the value ().

Similar syntax:

  • &1: a reference to a literal 1.
  • &[]: a reference to an empty slice.

Upvotes: 1

Related Questions