Help: move or clone?

First,My code is:

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {

    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        email: String::from("another@example.com"),
        ..user1
    };
    //Line 22 👇
    println!("{}\n",user2.username)
}

I use "struct update syntax" to create User2,and i make a break point at line 22.When i watch the value of User1.username and User2.username,I find that they have different address.But the rustlang tutorial say that User2.username was borrowed from User1,Ithink they should have the same address.QAQ,who can tell me way...Thank you.
My enviroment:
Ubuntu 20.04,x86_64 Linux 5.11.0-36-generic
cargo version:cargo 1.54.0 (5ae8d74b3 2021-06-22)
clang version:10.0.0-4ubuntu1
tools:Clion with Rust plugin
debugger:LLDB 12.0

From the book section on struct update syntax:

It’s often useful to create a new instance of a struct that uses most of an old instance’s values but changes some. You’ll do this using struct update syntax .

When it says that it "uses" most of the old instance, it doesn't mean that it borrows them. What it actually does is moves them.

For example, we can demonstrate this by attempting to access a field on user1 after doing this struct update.

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {

    let user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        email: String::from("another@example.com"),
        ..user1
    };
    //This is the line that is changed. Instead of `user2`, it tries to access `user1`. 👇
    println!("{}\n",user1.username)
}

The following compiler output is produced if we try to run this:

error[E0382]: borrow of moved value: `user1.username`
  --> src/main.rs:22:21
   |
17 |       let user2 = User {
   |  _________________-
18 | |         email: String::from("another@example.com"),
19 | |         ..user1
20 | |     };
   | |_____- value moved here
21 |       //This is the line that is changed. Instead of `user2`, it tries to access `user1`. 👇
22 |       println!("{}\n",user1.username)
   |                       ^^^^^^^^^^^^^^ value borrowed here after move
   |
   = note: move occurs because `user1.username` has type `String`, which does not implement the `Copy` trait
1 Like

Thank you!I did a deeper debug and I found that user1.username and user2.username have the different address,but the vec.buf.ptr of them have the same address!

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.