在共享的借用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 ...
构造,会发生什么?根据此博客文章,此隐式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的所有权,因为它只是借用了它的开头
But 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> IntoIterator for &'a Vec<T> {
fn into_iter(self) -> slice::Iter<'a, T> {
self.iter()
}
}
惊奇-它叫iter
!因此,您的问题的答案是:没有区别.
Surprise — it calls iter
! So the answer to your question is: there isn't a difference.
这篇关于在共享的借用Vec上的iter()和into_iter()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!