在 Rust 中,向量是迭代器吗? [英] In Rust, is a vector an Iterator?
问题描述
说一个向量(在其他集合类型中)是一个Iterator
是否准确?
Is it accurate to state that a vector (among other collection types) is an Iterator
?
例如,我可以通过以下方式循环一个向量,因为它实现了 Iterator
特征(据我了解):
For example, I can loop over a vector in the following way, because it implements the Iterator
trait (as I understand it):
let v = vec![1, 2, 3, 4, 5];
for x in &v {
println!("{}", x);
}
但是,如果我想使用属于 Iterator
特征的函数(例如 fold
、map
或 filter
) 为什么我必须首先在那个向量上调用 iter()
?
However, if I want to use functions that are part of the Iterator
trait (such as fold
, map
or filter
) why must I first call iter()
on that vector?
我的另一个想法是向量可以转换为 Iterator
,在这种情况下,上面的语法更有意义.
Another thought I had was maybe that a vector can be converted into an Iterator
, and, in that case, the syntax above makes more sense.
推荐答案
不,向量不是迭代器.
但它实现了 trait IntoIterator
,for
循环使用它来将向量转换为所需的迭代器.
But it implements the trait IntoIterator
, which the for
loop uses to convert the vector into the required iterator.
在 Vec
的文档中 可以看到 IntoIterator
是通过三种方式实现的:
In the documentation for Vec
you can see that IntoIterator
is implemented in three ways:
- 对于
Vec
,它被移动并且迭代器返回 T
类型的项目, - 对于共享引用
&Vec<T>
,其中迭代器返回共享引用&T
, - 对于
&mut Vec<T>
,返回可变引用.
- for
Vec<T>
, which is moved and the iterator returns items of typeT
, - for a shared reference
&Vec<T>
, where the iterator returns shared references&T
, - and for
&mut Vec<T>
, where mutable references are returned.
iter()
只是 Vec
中的一种方法,用于将 Vec
iter_mut()代码>
用于生成可变引用.
iter()
is just a method in Vec
to convert Vec<T>
directly into an iterator that returns shared references, without first converting it into a reference. There is a sibling method iter_mut()
for producing mutable references.
这篇关于在 Rust 中,向量是迭代器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!