【问题标题】:Mutating a struct's fields after a move移动后改变结构的字段
【发布时间】:2020-04-14 06:25:51
【问题描述】:

我对以下行为感到困惑:有人可以解释发生了什么吗?

考虑代码:

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 (!)
}

具体来说,我很困惑:

  1. 即使发生移动,也允许更新到p1.cx,
  2. p2.x返回的值其实不是更新后的5000,而是旧的100。

我期待新值,因为没有复制特征(因此移动), 所以期望只有一个单元格的更新值(5000) 应该打印。

但是,我一定错过了什么。有小费吗?提前致谢!

【问题讨论】:

    标签: rust alias move ownership-semantics


    【解决方案1】:

    现在禁止这样做。

    以前是允许的。然而,这是旧借用检查器中的一个错误,它已发出警告,然后在引入新的借用检查器 (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 版较长时间的错误(可能自该版本创建以来)。

    另见:

    【讨论】:

    • 谢谢,更有意义!我以为我有最新版本,显然没有,会更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2015-10-23
    相关资源
    最近更新 更多