为什么在将移动值的成员分配给?

时间:2016-03-16 23:12:36

标签: rust

我正在研究Rust by Example中的示例。

#[derive(Debug)]
struct Point {
    x: f64,
    y: f64,
}

#[derive(Debug)]
struct Rectangle {
    p1: Point,
    p2: Point,
}

fn main() {
    let mut point: Point = Point { x: 0.3, y: 0.4 };
    println!("point coordinates: ({}, {})", point.x, point.y);

    let rectangle = Rectangle {
        p1: Point { x: 1.0, y: 1.0 },
        p2: point,
    };

    point.x = 0.5; // Why does the compiler not break here,
    println!(" x is {}", point.x); // but it breaks here?

    println!("rectangle is {:?} ", rectangle);
}

我收到此错误(Rust 1.25.0):

error[E0382]: use of moved value: `point.x`
  --> src/main.rs:23:26
   |
19 |         p2: point,
   |             ----- value moved here
...
23 |     println!(" x is {}", point.x);
   |                          ^^^^^^^ value used here after move
   |
   = note: move occurs because `point` has type `Point`, which does not implement the `Copy` trait

我理解我将point提供给Rectangle对象,这就是为什么我无法再访问它,但为什么编译在println!上失败而不是在上一行?

2 个答案:

答案 0 :(得分:6)

真正发生的事情

fn main() {
    let mut point: Point = Point { x: 0.3, y: 0.4 };
    println!("point coordinates: ({}, {})", point.x, point.y);

    drop(point);

    {
        let mut point: Point;
        point.x = 0.5;
    }

    println!(" x is {}", point.x);
}

事实证明它已被称为issue #21232

答案 1 :(得分:4)

问题是编译器允许部分重新初始化结构,但之后整个结构不可用。即使结构只包含一个字段,即使您只是尝试读取刚刚重新初始化的字段,也会发生这种情况。

struct Test {
    f: u32,
}

fn main() {
    let mut t = Test { f: 0 };
    let t1 = t;
    t.f = 1;
    println!("{}", t.f);
}

这在issue 21232

中讨论