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;
My understanding is:
new_a is a copy of example.a so example still owns example.a.new_b now owns example.b since example.b was moved.Does rust implicitly copy example.a because it has Copy trait? And since example.b, which is a Vec, does not implement Copy trait, ownership of example.b is moved rather than copied?
Your understanding is correct. a is copied while b is moved. You can confirm this by trying to access the two fields afterwards.
println!("{:?}", example.a);
This prints 32. example.a is still accessible because it was copied, not moved.
println!("{:?}", example.b);
Accessing example.b fails to compile with the error message:
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
Which confirms exactly what you said, that example.b was moved because it doesn't implement the Copy trait.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With