3

私は次の行動に戸惑いました: 何が起こっているのか誰か説明してもらえますか?

次のコードを検討してください。

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)を出力する必要があるセルが1つだけあると予想していました。

しかし、私は何かが欠けているに違いありません。任意のヒント?前もって感謝します!

4

1 に答える 1

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 年版で長い間 (おそらく版の作成以来) エラーであったことにも注意してください。

以下も参照してください。

于 2019-12-22T19:47:03.507 に答える