struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn main() {
let mut user = User {
username: String::from("Paulx"),
email: String::from("paulx@gmail.io"),
sign_in_count: 0,
active: true,
};
let name = user.username;
user.username = String::from("Alix");
println!("{}", name);
}
Run Code Online (Sandbox Code Playgroud)
您将看到 是username从用户复制的变量name。变量name不是标量类型,为什么它可以复制呢?
我认为这里有一个误解。
你没有复制user.username,你把它移走了。
在您分配新的条目之前,user.username该条目user.username无效。
看这里:
struct User {
username: String,
}
fn main() {
let mut user = User {
username: String::from("Paulx"),
};
let name = user.username;
// Fails to compile!
println!("{}", user.username);
user.username = String::from("Alix");
// Works again.
println!("{}", user.username);
println!("{}", name);
}
Run Code Online (Sandbox Code Playgroud)
struct User {
username: String,
}
fn main() {
let mut user = User {
username: String::from("Paulx"),
};
let name = user.username;
// Fails to compile!
println!("{}", user.username);
user.username = String::from("Alix");
// Works again.
println!("{}", user.username);
println!("{}", name);
}
Run Code Online (Sandbox Code Playgroud)