[英]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.