在 Rust 中,向量是迭代器吗? [英] In Rust, is a vector an Iterator?

查看:17
本文介绍了在 Rust 中,向量是迭代器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说一个向量(在其他集合类型中)是一个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 特征的函数(例如 foldmapfilter) 为什么我必须首先在那个向量上调用 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 IntoIteratorfor 循环使用它来将向量转换为所需的迭代器.

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 type T,
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆