rust - 为什么将移动值的成员分配给时编译不会失败?

标签 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 上失败! 而不是上一行的赋值?

最佳答案

真正发生了什么

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 .

关于rust - 为什么将移动值的成员分配给时编译不会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566669/

相关文章:

rust - 使用结构实现中的特征方法

rust - 在actix线程中进行同步http客户端访存

docker - 优化 Docker 中的 cargo 构建时间

vector - rust 是否可以为不同的数据结构提供统一的 Iterator 接口(interface)?

rust - rust-具有特征的泛型函数的返回类型

rust - 带有产生流的异步fn的此通用结构遇到麻烦

rust - 在匹配 `Result` 时使用 if-let 绑定(bind)并仍然能够捕获错误的惯用方法是什么?

rust - 如何重新启动基板节点

sorting - 如何对向量的一部分进行排序?

reference - 编写二叉搜索树时,参数类型 `T` 可能生命周期不够长