"cannot move out of index of" 是什么意思?

What does "cannot move out of index of" mean?

我正在玩 Rust,我正在尝试使用以下代码访问第一个命令行参数:

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let dir = args[1];
}

我得到这个错误:

error[E0507]: cannot move out of indexed content
 --> src/main.rs:5:15
  |
5 |     let dir = args[1];
  |         ---   ^^^^^^^ cannot move out of indexed content
  |         |
  |         hint: to prevent move, use `ref dir` or `ref mut dir`

或者在更高版本的 Rust 中:

error[E0507]: cannot move out of index of `std::vec::Vec<std::string::String>`
 --> src/main.rs:5:15
  |
5 |     let dir = args[1];
  |               ^^^^^^^
  |               |
  |               move occurs because value has type `std::string::String`, which does not implement the `Copy` trait
  |               help: consider borrowing here: `&args[1]`

如果我将其更改为 let ref dir,它会编译,但我不明白发生了什么。有人可以解释一下 "indexed content" 是什么意思吗?

当您使用索引运算符 ([]) 时,您会在索引位置获得实际对象。您没有得到参考、指针或副本。由于您尝试使用 let 绑定来绑定该对象,Rust 会立即尝试移动(或复制,如果实现了 Copy 特征)。

在您的示例中,env::args()String 的迭代器,然后将其收集到 Vec<String> 中。这是拥有的字符串的拥有向量,并且拥有的字符串不能自动复制。

您可以使用 let ref 绑定,但更惯用的替代方法是引用索引对象(注意 & 符号):

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let ref dir = &args[1];
    //            ^
}

不允许隐式移出 Vec,因为这会使它处于无效状态 — 一个元素被移出,其他元素则没有。如果你有一个可变的Vec,你可以使用像Vec::remove这样的方法来取出单个值:

use std::env;

fn main() {
    let mut args: Vec<_> = env::args().collect();
    let dir = args.remove(1);
}

另请参阅:


对于您的特定问题,您也可以只使用 Iterator::nth:

use std::env;

fn main() {
    let dir = env::args().nth(1).expect("Missing argument");
}