How does this `let` work?

Hello,
Please help to explain what does let Person { name, ref age } = person; do exactly in the snippet below? And of cause why we can access name and age directly from println!? Thank you.

fn main() {
    #[derive(Debug)]
    struct Person { name: String, age: Box<u8>, }
    let person = Person { name: String::from("Alice"), age: Box::new(20), };

    let Person { name, ref age } = person;

    println!("The person's age is {}", age);
    println!("The person's name is {}", name);
}

This is a type of pattern syntax usually referred to as destructuring:

1 Like

yah, this below saying helps. Thanks.

We can also use patterns to destructure structs, enums, and tuples to use different parts of these values. Let’s walk through each value.

Here's my favorite post on the topic. (Even though it doesn't cover ref patterns or binding modes.)

1 Like