2

Caveat: I'm new to Rust, so pardon any ignorance.

I have a function that accepts a reference to a vector. It then creates an iterator from that vector and does processing on its values.

Code:

fn new(args: &Vec<String>) -> Result<Config, &str> {
        let mut args_iter = args.iter(); //create iterator
        args_iter.next(); //skip the 0th item

        let query = match args_iter.next() {
            Some(arg) => *arg, //BREAKS
            None => return Err("no query"),
        };

        let file = match args_iter.next() {
            Some(arg) => arg.clone(), //WORKS
            None => return Err("no file"),
        };

        //more stuff
    }

Now I'm getting this error:

move occurs because `*arg` has type `String`, which does not implement the `Copy` trait

Which gets solved if I change *arg to arg.clone().

Can someone help me understand why? I thought that by creating an iterator inside the function, the function owns the iterator and should be able to mutate/move its values as it pleases?

ilmoi
  • 1,994
  • 2
  • 21
  • 45

1 Answers1

3

I thought that by creating an iterator inside the function, the function owns the iterator and should be able to mutate/move its values as it pleases?

It owns the iterator but the iterator may or may not own it’s values.

Here the iterator comes from an &Vec, so the current function does not own any of the data being iterated upon, which means the iterator only hands out &String: references owned by a caller.

Just don’t dereference the &String, there is no reason to in what little code you show.

That aside, your match could easily be replaced by .ok_or(msg)?.

And your output should probably be &'static str (or a Cow), as defined rustc thinks that there is a relationship between the inputs and the error message. Though I have to say I’d use an enum, whether contextual data is added or not. That allows finer error selection and implementing Error which can be useful.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • 1
    If you don't dereference (but also don't clone) it breaks too. But I get your point about owning the vector but not the values inside the vector. Thanks for commenting. – ilmoi May 06 '21 at 03:55