【问题标题】:What does "cannot move out of index of" mean?“不能移出索引”是什么意思?
【发布时间】:2015-01-12 14:59:29
【问题描述】:

我正在使用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,它会编译,但我不知道发生了什么。有人能解释一下“索引内容”是什么意思吗?

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    在您的示例中,env::args()Strings 的迭代器,然后将其收集到 Vec&lt;String&gt; 中。这是自有字符串的自有向量,自有字符串不能自动复制。

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

    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");
    }
    

    【讨论】:

    • 如果我拥有数组,并且想要获得数组中单个值的所有权(并消耗数组的所有权)怎么办?
    • 如果是Vec可以使用remove方法,否则可以mem::replace使用虚拟值。
    • vec.into_iter().nth(1).expect("Missing element") 工作
    • 备注:Index 特征看起来应该返回一个引用,但正如这个答案所说,它没有。另见stackoverflow.com/questions/27879161/…
    猜你喜欢
    • 2014-09-28
    • 2018-06-21
    • 1970-01-01
    • 2010-09-16
    • 2022-11-25
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多