Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust Partial Move syntax

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)?

>Solution :

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 name and age and initializes them with person.name and person.age. Because of the ref the age variable will have the type &Box<u8> and point to person.age.

At this point the struct person is partially moved out, because of the move of person.name, so you cannot use it anymore. But you can still use person.age because this was not moves out because of the ref.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading