【发布时间】:2018-09-19 07:41:21
【问题描述】:
我正在研究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! 而不是上一行的赋值?
【问题讨论】:
-
我猜“使用移动的值”可以解释为您尝试读取它的值的点。分配给它并不会真正改变 Rust 在“技术”意义上的保证,只有当您尝试使用移动的值时。也就是说,我自己对其中的大部分内容还不够了解,所以我很想听听更了解这方面的人的意见。
-
感觉像编译器错误。更有趣的是
let p2 = point; point.x = 0.5; println!(" x is {}", p2.x);编译良好并打印 0.3,所以point.x = 0.5;什么都不做 -
@qthree 这完全可以预料; Rust 使用值类型,而不是引用类型。
标签: rust