gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:43:19 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com