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