发生移动是因为 `*arg` 具有类型 `String`,它没有实现 `Copy` 特性

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

警告:我是 Rust 新手,请原谅我的无知。

我有一个接受向量引用的函数。然后它从该向量创建一个迭代器并对它的值进行处理。

代码:

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
    }

现在我收到这个错误:

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

如果我将 *arg 更改为 arg.clone(),问题就解决了。

谁能帮我理解为什么?我认为通过在函数内部创建迭代器,函数拥有迭代器并且应该能够 mutate/move 它的值随心所欲?

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?

它拥有迭代器,但迭代器可能拥有也可能不拥有它的值。

这里的迭代器来自一个&Vec,所以当前函数不拥有任何被迭代的数据,这意味着迭代器只分发&String:调用者拥有的引用.

只是不要取消对 &String 的引用,没有理由在您显示的代码中取消引用。

除此之外,您的 match 很容易被 .ok_or(msg)? 取代。

而你的输出可能应该是 &'static str(或 Cow),因为 rustc 认为输入和错误消息之间存在关系。尽管我不得不说我会使用枚举,无论是否添加上下文数据。这允许更精细的错误选择和实施 Error 这可能很有用。