我正在研究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

我知道我给Rectangle对象加了point,这就是为什么我不能再访问它,但为什么编译在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相关问答推荐

给定使用newype习语定义的类型上的铁 rust Vec,有没有方法获得底层原始类型的一部分?

为什么我需要在这个代码示例中使用&

如何找到一个数字在二维数组中的位置(S)?

具有对同一类型的另一个实例的可变引用的

除了调用`waker.wake()`之外,我如何才能确保future 将再次被轮询?

如何实现Serde::Ser::Error的调试

在Rust 中移动原始指针的靶子安全吗

你能在Rust中弃用一个属性吗?

为什么 `Deref` 没有在 `Cell` 上实现?

为什么实现特征的对象期望比具体对象有更长的生命周期?

Rust:为什么 &str 不使用 Into

write_buffer 不写入缓冲区而是输出零 WGPU

可选包装枚举的反序列化

tokio::spawn 有和没有异步块

我可以禁用发布模式的开发依赖功能吗?

Rust: 目标成员属于哪个"目标家族"的列表是否存在?

使用 Rust 从 Raspberry Pi Pico 上的 SPI 读取值

从 HashMap>, _> 中删除的生命周期问题

切片不能被 `usize` 索引?

使用部分键从 Hashmap 中检索值