Explain this struct implementation

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?


let &Inches(inches) = self;

is destructuring.

The variable self has the type Inches(i32) so that line takes the i32 value at self.0 and brings it into scope as a variable named inches. It's the same as calling it self.0 but with a name that explains what it is instead of just calling it "field zero".

1 Like

This is equivalent to

let inches = self.0;

but uses destructuring assignment, rather than referencing the field. I would assume that the author wrote it this way to mirror the declaration of the structure, to make it clear what the otherwise-unlabelled tuple field represents.

1 Like

Strictly speaking, to *(self.0), due to the reference-pattern on the left side.