What does “cannot move out of index of” mean?

后端 未结 1 2044
我在风中等你
我在风中等你 2020-11-27 06:34

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         


        
相关标签:
1条回答
  • 2020-11-27 06:52

    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).

    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.

    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];
        //            ^
    }
    

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

    See also:

    • What is the return type of the indexing operation?

    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");
    }
    
    0 讨论(0)
提交回复
热议问题