[英]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)
}
}
I understand that the function signature takes a reference of the Inches struct as a parameter, what does the first line in the function definition mean?我知道 function 签名将 Inches 结构的引用作为参数,function 定义中的第一行是什么意思?
In the let a = b
syntax, a
doesn't just have to be an indentifier for a new variable, it can also be a pattern much like in match
arms:在
let a = b
语法中, a
不仅必须是新变量的标识符,它还可以是一个模式,很像match
arm 中的模式:
let a = 0;
let (a, c) = (0, 1);
let &a = &0;
let Inches(a) = Inches(0);
So what you see here is self
being matched as a &Inches
and pulling out the inner value into a new variable called "inches".所以你在这里看到的是
self
被匹配为&Inches
并将内部值提取到一个名为“inches”的新变量中。
This statement is probably more universally readable as:该语句可能更具普遍性,因为:
let inches = self.0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.