I am learning rust currently, and I found some interesting behavior about function returning structure.
Suppose struct User is defined like this.
struct User {
email: String,
username: String,
age: i32,
}
And a function to generate the User struct defined like this.
fn build_user(email: String, username: String, age: i32) -> User {
let built_user = User {
email,
username,
age,
};
println!("&built_user : {:p}", &built_user);
built_user
}
So, now in function main, I print the pointer of build_user's return value.
fn main() {
let user1 = build_user(String::from("asd"), String::from("def"), 32);
println!("&user1 : {:p}", &user1);
}
If you run it you will see two pointers printed out is same!
Since assigning a struct to new variable (either copy or move) will make new struct object on stack, any other assignment like
let user2 = user1;
will result different pointers.
And even more weird thing is that if structure only contains types with copy trait, something like this,
struct User {
age: i32,
login_counts: i32,
}
would behave differently and two pointers will not be equal.
I experimented a lot applying small changes to struct and fn, but this explicit case (struct that doesn't implements copy trait / fn returning only struct, not tuple) seems to be the only one behaving differently to normal assignment.
Can anyone explain why it behaves like this? Thanks