我在玩 Rust 并找到了以下示例:
fn main() {
let mut x = [3, 4, 5].to_vec();
x;
println!("{:?}", x);
}
Run Code Online (Sandbox Code Playgroud)
编译器告诉我
18 | let mut x = [3, 4, 5].to_vec();
| ----- move occurs because `x` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
...
21 | x;
| - value moved here
22 | println!("{:?}", x);
| ^ value borrowed here after move
Run Code Online (Sandbox Code Playgroud)
似乎x;引起的语句x移到了某个地方,之后就不能使用了。移动目的地在哪里,这里究竟发生了什么?
我四处搜索,找不到任何解释这一点的信息。也许我使用了错误的关键字。
顺便说一句,我正在使用这个版本的 Rust: rustc 1.41.0-nightly (99b89533d 2019-12-16)
x;是一个表达式语句:
表达式语句是对表达式求值并忽略其结果的语句。
这里的表达式又是一个位置表达式,它:
移出计算为局部变量的位置表达式,该位置被取消初始化,并且在重新初始化之前无法再次读取。
所以在那之后你就不能再使用它了。事实上,如果你编译如下:
fn main() {
let x = vec![42];
x;
}
Run Code Online (Sandbox Code Playgroud)
到米尔:
fn main() -> () {
let mut _0: (); // return place in scope 0 at src/main.rs:1:11: 1:11
let _1: std::vec::Vec<i32>; // "x" in scope 0 at src/main.rs:2:9: 2:10
...
bb1: {
StorageDead(_2); // bb1[0]: scope 0 at <::alloc::macros::vec macros>:2:62: 2:63
StorageLive(_5); // bb1[1]: scope 1 at src/main.rs:3:5: 3:6
_5 = move _1; // bb1[2]: scope 1 at src/main.rs:3:5: 3:6
drop(_5) -> bb2; // bb1[3]: scope 1 at src/main.rs:3:6: 3:7
}
}
Run Code Online (Sandbox Code Playgroud)
您可以清楚地看到它被移动到一个临时变量中,并且该临时变量被迅速删除。