【问题标题】:What is the purpose of the &() syntax?&() 语法的目的是什么?
【发布时间】:2020-11-22 21:53:01
【问题描述】:

我一直在使用 rust 库 Vulkano 编写一些 Vulkan 代码,并且遇到了以下 sn-p:

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

我在这里专门询问第三个参数 - 在ComputePipeline::new 的实现中,它被列为:

/// 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,
{
    ...
}

这里的&amp;() 语法是什么?对单位类型的引用?

【问题讨论】:

  • 对单元类型的引用? - 就是这样
  • 谢谢@kmdreko,这听起来像是一个反问,但我不确定,而对于 Rust,我发现确保你真正了解正在发生的事情是值得的。

标签: rust syntax


【解决方案1】:

是的,它是对一个单位的引用。 这里需要这样做,因为ComputePipeline::new 是通用的:

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

specialization 的类型是与shader 的类型相关的关联类型。为shader 提供的值类型将决定specialization 的类型,具体取决于EntryPointAbstract 的实现。

在您提供的示例代码中,尚不清楚shader.main_entry_point() 具有什么类型,但它必须具有EntryPointAbstract 的实现,并且其关联的SpecializationConstants 类型是()

为了使类型检查起作用,您必须将&amp;() 传递给specialization,即使它很可能表示“没有值”。编译器可以对此进行优化,因此在运行时,该值不存在,并且该函数实际上只有两个参数。

据推测,EntryPointAbstract 的其他实现对SpecializationConstants 有更有趣的类型。

【讨论】:

  • 感谢您的解释!所以只是为了澄清 - 在这里传递对单元类型的引用在运行时仍然代表“无”,这是编译时兼容性/类型检查的结果?
  • @NicBarker 有点,单位不是完全“无”(取决于通常是Option::None! 的上下文),但由于它始终是相同的值,它不携带任何信息, 所以它倾向于在没有信息发送或返回时使用(例如,在 C 或 Java 具有 void 伪返回类型的情况下,rust 函数使用 ())。
【解决方案2】:

Vulkano 的 ComputePipeline::new 将关联类型 SpecializationConstants 的引用作为其第三个参数:

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

在这种情况下,关联类型是零元组,或the unit type

type SpecializationConstants = ()

传递对值的引用意味着添加&amp;,因此对单元类型的引用看起来像这样&amp;()

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

【讨论】:

    【解决方案3】:

    [是] 对单元类型的引用吗?

    就是这样。它只是将引用 &amp; 传递给值 ()

    类似的语法:

    • &amp;1:对文字 1 的引用。
    • &amp;[]:对空切片的引用。

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      相关资源
      最近更新 更多