繁体   English   中英

在 Rust 中解释这个结构体的实现

[英]Explain this struct implementation in Rust

// `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)
    }
}

我知道 function 签名将 Inches 结构的引用作为参数,function 定义中的第一行是什么意思?

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

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

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

该语句可能更具普遍性,因为:

let inches = self.0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM