user15205786
user15205786

Reputation:

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?

Upvotes: 0

Views: 90

Answers (1)

kmdreko
kmdreko

Reputation: 60437

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;

Upvotes: 4

Related Questions