在 Rust 中,带有单个变量名和分号的语句是什么意思?
What does a statement with a single variable name and a semicolon mean in Rust?
我正在玩 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)
x;
是 an expression statement 即:
An expression statement is one that evaluates an expression and ignores its result.
这里的表达式依次是a place expression which:
Moving out of a place expression that evaluates to a local variable, the location is deinitialized and cannot be read from again until it is reinitialized.
所以之后你就不能再使用它了。事实上,如果你编译如下:
fn main() {
let x = vec![42];
x;
}
至 MIR:
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
}
}
你可以清楚地看到它被移动到一个临时变量中,并且那个临时变量很快就被删除了。
我正在玩 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)
x;
是 an expression statement 即:
An expression statement is one that evaluates an expression and ignores its result.
这里的表达式依次是a place expression which:
Moving out of a place expression that evaluates to a local variable, the location is deinitialized and cannot be read from again until it is reinitialized.
所以之后你就不能再使用它了。事实上,如果你编译如下:
fn main() {
let x = vec![42];
x;
}
至 MIR:
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
}
}
你可以清楚地看到它被移动到一个临时变量中,并且那个临时变量很快就被删除了。