为什么将移动值的成员分配给编译不会失败? [英] Why does compilation not fail when a member of a moved value is assigned to?

查看:44
本文介绍了为什么将移动值的成员分配给编译不会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working through examples in 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):

I get this error (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 上失败! 而不是上一行的赋值?

I understand that I gave point to the Rectangle object and that is why I can no longer access it, but why does the compilation fail on the println! and not the assignment on the previous line?

推荐答案

实际发生的事情

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);
}

事实证明,它已经被称为问题 #21232.

It turns out that it's already known as issue #21232.

这篇关于为什么将移动值的成员分配给编译不会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆