簡體   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