Copy with `struct update`

struct Person {
    nick_name: String,
    name: String,
}

fn main() {
    let person1 = Person {
        name: String::from("Person 1"),
        nick_name: String::from("Person 2"),
    };

    let person2 = Person {
        ..person1 // <=========== Using struct update
    };

    println!("{}, {}", person1.name, person2.name); // ERROR,
}

How to pass the values of person1 to person2 as a copy rather than moving ownership?

Is there any built in operator or any other roundabout way to implement this?

String is not Copy because it refers to a heap allocation. But you can use Clone:

#[derive(Clone)]
struct Person {
    nick_name: String,
    name: String,
}

fn main() {
    let person1 = Person {
        name: String::from("Person 1"),
        nick_name: String::from("Person 2"),
    };

    let person2 = Person {
        ..person1.clone() // <=========== Using struct update
    };

    println!("{}, {}", person1.name, person2.name);
}
3 Likes
struct Person {
    nick_name: String,
    name: String,
}

impl Person {
    fn clone(&self) -> Person {
        Person {
            name: self.name.clone(),
            nick_name: self.nick_name.clone(),
        }
    }
}

fn main() {
    let person1 = Person {
        name: String::from("Person 1"),
        nick_name: String::from("Person 2"),
    };

    let person3 = Person {
        ..person1.clone()
    };

    println!("{}, {}", person1.name, person3.name);
    
}

You mean like this?

No, you shouldn't define your own clone() method. The clone() method you should be using is the one on the Clone trait, and you can make Person implement Clone automatically by putting #[derive(Clone)] right above the struct Person line.

3 Likes

So basically just prepending the macro #[derive(Clone)] to a struct will allow to clone the properties.

Thanks.

OOPS!! Missed out the Macro prepended to the struct. Now, I am getting the desired output.

Thank you.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.