struct Haha {
pub a: u32,
pub b: Vec<u32>,
}let example = Haha {
a: 32,
b: vec![1],
};
let new_a = example.a;
let new_b = example.b;我的理解是:
new_a是example.a的副本,所以自从example.b被移动以来,example仍然拥有example.b。锈病是因为example.a具有Copy特性而隐式复制Copy吗?而且,由于example.b,即Vec,并不实现Copy特性,所以example.b的所有权是移动而不是复制的?
发布于 2020-10-16 14:34:18
你的理解是正确的。a被复制,而b被移动。您可以通过随后尝试访问这两个字段来确认这一点。
println!("{:?}", example.a);这个打印32。example.a仍然是可访问的,因为它是复制的,而不是移动的。
println!("{:?}", example.b);访问example.b时无法使用错误消息进行编译:
error[E0382]: borrow of moved value: `example.b`
--> src/main.rs:13:22
|
12 | let _new_b = example.b;
| --------- value moved here
13 | println!("{:?}", example.b);
| ^^^^^^^^^ value borrowed here after move
|
= note: move occurs because `example.b` has type `std::vec::Vec<u32>`, which does not implement the `Copy` trait这证实了您所说的,example.b之所以被移动是因为它没有实现Copy特性。
https://stackoverflow.com/questions/64391055
复制相似问题