共享的借用 Vec 上的 iter() 和 into_iter() 之间的区别? [英] Difference between iter() and into_iter() on a shared, borrowed Vec?
问题描述
我正在阅读 Rust 101 教程,作者在其中谈到与传递给函数的 Vec
对象的示例共享借用.下面是本教程所教内容的稍微改编的 MWE.有趣的部分是 vec_min
中的 v.iter()
.作者写道:
I am reading the Rust 101 tutorial, where the author talks about shared borrowing with the example of a Vec
object passed to a function. Below is a slightly adapted MWE of what the the tutorial is teaching. The interesting part is v.iter()
in vec_min
. The author writes:
这一次,我们明确地为向量 v
请求一个迭代器.iter
方法借用它工作的向量,并提供元素的共享借用.
This time, we explicitly request an iterator for the vector
v
. The methoditer
borrows the vector it works on, and provides shared borrows of the elements.
但是,如果我在共享对象上使用 for ... in ...
构造会发生什么?根据 this blog post,这个隐式 for 循环使用 into_iter()
,取得 v
的所有权.但它并不能真正获得该函数中 v
的所有权,因为它只是一开始就借用了它,对吧?
But what happens if I use a for ... in ...
construction on an object which is shared? According to this blog post, this implicit for loop uses into_iter()
, taking ownership of v
. But it cannot really take ownership of the v
in that function, since it has only borrowed it to begin with, right?
有人可以向我解释应用于借用对象的 into_iter()
和 iter()
之间的区别吗?
Can somebody explain the difference between into_iter()
and iter()
applied to a borrowed object to me?
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();
}
推荐答案
没有区别.
它不能真正获得该函数中 v
的所有权,因为它只是在开始时借用了它
it cannot really take ownership of the
v
in that function, since it has only borrowed it to begin with
它绝对可以拥有v
,因为那是一个&Vec
.请注意此处的精确语义 - 您获得了引用的所有权,而不是被引用项的所有权.
It absolutely can take ownership of v
, because that's a &Vec
. Note the precise semantics here - you are taking ownership of the reference, not of the referred-to item.
如果您查看 IntoIterator的实现者代码>
,可以找到:
If you check out the implementors of IntoIterator
, you can find:
impl<'a, T> IntoIterator for &'a Vec<T>
还有 来源:
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 vec
和 vec.iter_mut()
The same logic applies for &mut vec
and vec.iter_mut()
这篇关于共享的借用 Vec 上的 iter() 和 into_iter() 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!