我正在玩Rust,并发现了以下示例:
fn main() {
let mut x = [3, 4, 5].to_vec();
x;
println!("{:?}", x);
}编译器告诉我
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似乎x;导致x迁移到了某个地方,之后就不能使用它了。移动目的地在哪里,到底发生了什么?
我到处找都找不到解释这件事的任何信息。也许我用错了关键字。
顺便说一下,我正在使用这个版本的Rust:rustc 1.41.0-nightly (99b89533d 2019-12-16)
发布于 2019-12-21 20:32:59
x;是表达式语句,即:
表达式语句是计算表达式并忽略其结果的语句。
这里的表达式依次是地方表达,它:
从计算结果为局部变量的place表达式中移出,该位置将被重新初始化,并且在重新初始化之前不能再次读取该位置。
在那之后你就不能再用它了。实际上,如果您编译了以下内容:
fn main() {
let x = vec![42];
x;
}致和平号:
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
}
}您可以清楚地看到,它被移动到一个临时变量中,并且该临时变量被迅速删除。
https://stackoverflow.com/questions/59439201
复制相似问题