简体   繁体   中英

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?

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 = 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".

This statement is probably more universally readable as:

let inches = self.0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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