I was puzzled by the following behavior: could someone explain what is going on?
Consider the code:
struct Point {
cx : u32,
}
fn main() {
let mut p1 = Point { cx: 100 };
let p2 = p1;
p1.cx = 5000;
// println!("p1.x = {}", p1.cx); // disallowed as p1.cx is "moved" ... ok
println!("p2.x = {}", p2.cx); // ==> prints 100 (!)
}
Specifically, I was puzzled that:
- The update to
p1.cx
is allowed even though the move has occurred, - The value returned by
p2.x
is not in fact the updated 5000, but the old100
.
I was expecting the new value as there is no copy-trait (hence the move),
so was expecting there is just a single cell whose updated value (5000
)
should be printed.
However, I must be missing something. Any tips? Thanks in advance!
This is now forbidden.
It used to be allowed. However this was an error in the old borrow checker, and it has been made a warning then an error with the introduction of the new borrow checker (NLL).
For example, with
rustc 1.39.0
and the 2015 edition you get the following warning:rustc 1.40.0
turned it into an error:Note also that this was an error with the 2018 edition for a longer time (possibly since the creation of the edition).
See also:
E0729