我为以下行为感到困惑:有人可以解释发生了什么事吗?
考虑代码:
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 (!)
}
具体来说,我感到困惑:
p1.cx
,p2.x
返回的值实际上不是更新的5000,而是旧的100
。由于没有复制特性,我一直期待新的价值(因此有所举动),
因此,原本以为只有一个单元格的更新值(5000
)
应该打印出来。
但是,我必须缺少一些东西。有小费吗?预先感谢!
答案 0 :(得分:7)
现在禁止这样做。
它曾经被允许。但是,这是旧借阅检查器中的一个错误,并且在引入新借阅检查器(NLL)时被警告,然后出错。
例如,在rustc 1.39.0
和2015版中,您会收到以下警告:
warning[E0382]: assign to part of moved value: `p1`
--> a.rs:8:5
|
6 | let mut p1 = Point { cx: 100 };
| ------ move occurs because `p1` has type `Point`, which does not implement the `Copy` trait
7 | let p2 = p1;
| -- value moved here
8 | p1.cx = 5000;
| ^^^^^^^^^^^^ value partially assigned here after move
|
= warning: this error has been downgraded to a warning for backwards compatibility with previous releases
= warning: this represents potential undefined behavior in your code and this warning will become a hard error in the future
= note: for more information, try `rustc --explain E0729`
rustc 1.40.0
变成了错误:
error[E0382]: assign to part of moved value: `p1`
--> src/main.rs:7:5
|
5 | let mut p1 = Point { cx: 100 };
| ------ move occurs because `p1` has type `Point`, which does not implement the `Copy` trait
6 | let p2 = p1;
| -- value moved here
7 | p1.cx = 5000;
| ^^^^^^^^^^^^ value partially assigned here after move
error: aborting due to previous error
还请注意,这是2018年版较长时间的错误(可能是自该版本创建以来)。
另请参阅:
E0729
如先前所宣布,2015版中以前的任何NLL警告现在都是硬错误。