gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:47:46 36 4
gpt4 key购买 nike

我正在阅读 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/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com