什么是“不能移出"的索引?意思是? [英] What does "cannot move out of index of" mean?

查看:18
本文介绍了什么是“不能移出"的索引?意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am playing with Rust, and I'm trying to access the first command line argument with this code:

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 中:

Or in later versions of 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,它会编译,但我不明白发生了什么.有人能解释一下索引内容"是什么意思吗?

If I change it to let ref dir, it compiles, but I don't grok what's going on. Could someone explain what "indexed content" means?

推荐答案

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

When you use an index operator ([]) you get the actual object at index location. You do not get a reference, pointer or copy. Since you try to bind that object with a let binding, Rust immediately tries to move (or copy, if the Copy trait is implemented).

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

In your example, env::args() is an iterator of Strings which is then collected into a Vec<String>. This is an owned vector of owned strings, and owned strings are not automatically copyable.

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

You can use a let ref binding, but the more idiomatic alternative is to take a reference to the indexed object (note the & symbol):

use std::env;

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

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

Implicitly moving out of a Vec is not allowed as it would leave it in an invalid state — one element is moved out, the others are not. If you have a mutable Vec, you can use a method like Vec::remove to take a single value out:

use std::env;

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

另见:

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

For your particular problem, you can also just use Iterator::nth:

use std::env;

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

这篇关于什么是“不能移出"的索引?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆