I am reading this official example from rust-by-example:
fn main() {
#[derive(Debug)]
struct Person {
name: String,
age: Box<u8>,
}
let person = Person {
name: String::from("Alice"),
age: Box::new(20),
};
// `name` is moved out of person, but `age` is referenced
// **What is this syntax here and why does it work?
let Person { name, ref age } = person;
println!("The person's age is {}", age);
println!("The person's name is {}", name);
// Error! borrow of partially moved value: `person` partial move occurs
//println!("The person struct is {:?}", person);
// `person` cannot be used but `person.age` can be used as it is not moved
println!("The person's age from person struct is {}", person.age);
}
This line of code:
let Person { name, ref age } = person;
caught me off guard; I understand,
let person_a = Person {name: String::from("Bob"), age: Box::new(30)},
and,
let moved_person_a = person_a.
That line of code looks foreign to me.
Secondly, we are accessing age and name directly as if we have defined them directly in the scope of main. Does this have anything to do with the line of code above? Or this is how Rust works (i.e. Accessing member properties of a object without the presence of the object, which already sounds a bit insane to me)?
The line in question is a pattern for destructing structs. See https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#destructuring-structs.
It creates two variables
nameandageand initializes them withperson.nameandperson.age. Because of therefthe age variable will have the type&Box<u8>and point toperson.age.At this point the struct
personis partially moved out, because of the move ofperson.name, so you cannot use it anymore. But you can still useperson.agebecause this was not moves out because of theref.