iterator - 共享借用的 Vec 上 iter() 和 into_iter() 的区别?

标签 iterator rust shared

我正在阅读 Rust 101 tutorial ,其中作者以传递给函数的 Vec 对象为例讨论了共享借用。下面是本教程所教内容的稍微改编的 MWE。有趣的部分是 vec_min 中的 v.iter()。作者写道:

This time, we explicitly request an iterator for the vector v. The method iter borrows the vector it works on, and provides shared borrows of the elements.

但是如果我在共享对象上使用 for ... in ... 构造会发生什么?根据this blog post ,这个隐式 for 循环使用 into_iter(),获取 v 的所有权。但它不能真正取得该函数中 v 的所有权,因为它只是从一开始就借用了它,对吗?

有人可以向我解释 into_iter() 和应用于借用对象的 iter() 之间的区别吗?

enum NumberOrNothing {
    Number(i32),
    Nothing,
}
use self::NumberOrNothing::{Number,Nothing};

impl NumberOrNothing {
    fn print(self) {
        match self {
            Nothing => println!("The number is: <nothing>"),
            Number(n) => println!("The number is: {}", n),
        };
    }
}

fn vec_min(v: &Vec<i32>) -> NumberOrNothing {
    fn min_i32(a: i32, b: i32) -> i32 {
        if a < b {a} else {b}
    }

    let mut min = Nothing;
    for e in v.iter() {
    //Alternatively implicitly and with *e replaced by e:
    //for e in v {
        min = Number(match min {
            Nothing => *e,
            Number(n) => min_i32(n, *e),
        });
    }
    min
}

pub fn main() {
    let vec = vec![18,5,7,2,9,27];
    let foo = Nothing;
    let min = vec_min(&vec);
    let min = vec_min(&vec);
    min.print();
}

最佳答案

没有区别。

it cannot really take ownership of the v in that function, since it has only borrowed it to begin with

它绝对可以取得v的所有权,因为那是一个&Vec。请注意此处的精确语义 - 您正在取得所有权引用,而不是所引用项目的所有权。

如果您查看 implementors of IntoIterator ,你可以发现:

impl<'a, T> IntoIterator for &'a Vec<T>

还有 source for that :

impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

    fn into_iter(self) -> slice::Iter<'a, T> {
        self.iter()
    }
}

惊喜——它调用了 iter!

同样的逻辑适用于 &mut vecvec.iter_mut()

关于iterator - 共享借用的 Vec 上 iter() 和 into_iter() 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32234954/

相关文章:

c++ - STL 映射迭代器运行时错误

rust - 为什么定义 RUSTFLAGS 会导致 .cargo/config 中的 rustflags 被忽略?

java服务与资源共享

C++:如何创建两个相互依赖的共享库?

java - 逐一显示Arraylist的元素

java - Java中的Hashtable迭代和删除

c++ - iterator::difference_types 是否独立于系统

rust - 如何使用 serde 将 Rust 对象序列化为 Rust 文字?

rust - 进行多次可变和不可变借贷的最佳实践是什么? [复制]

java - 共享首选项未保存或循环不起作用