【问题标题】:Explain this struct implementation in Rust用 Rust 解释这个结构实现
【发布时间】:2021-08-23 23:43:24
【问题描述】:
// `Inches`, a tuple struct that can be printed
#[derive(Debug)]
struct Inches(i32);

impl Inches {
    fn to_centimeters(&self) -> Centimeters {
        let &Inches(inches) = self;

        Centimeters(inches as f64 * 2.54)
    }
}

我理解函数签名是以Inches结构的引用作为参数,函数定义中的第一行是什么意思?

【问题讨论】:

    标签: struct rust implementation


    【解决方案1】:

    let a = b 语法中,a 不仅必须是新变量的标识符,它还可以是一个模式,很像match arm: p>

    let a = 0;
    let (a, c) = (0, 1);
    let &a = &0;
    let Inches(a) = Inches(0);
    

    所以您在这里看到的是 self 被匹配为 &Inches 并将内部值提取到一个名为“英寸”的新变量中。

    这句话可能更通俗易懂:

    let inches = self.0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2020-01-11
      • 2011-07-12
      • 2012-02-06
      • 1970-01-01
      相关资源
      最近更新 更多