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

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

问题描述

说明向量(在其他集合类型中)是迭代器是否准确?

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);
}

但是,如果我想使用属于<$ c的函数$ c> Iterator trait(例如 fold map 过滤器)为什么我必须先在该向量上调用 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.

推荐答案

不,向量不是迭代器。

但它实现了特征 IntoIterator ,其中 for loop用于将向量转换为所需的迭代器。

But it implements the trait IntoIterator, which the for loop uses to convert the vector into the required iterator.

Vec 的文档,你可以看到 IntoIterator 以三种方式实现:for Vec< T> ,w hich被移动,迭代器返回 T 类型的项目,共享参考& Vec< T> ,其中迭代器返回共享引用& T ,以及& mut Vec< T> ,其中返回可变引用。

In the documentation for Vec you can see that IntoIterator is implemented in three ways: 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< T> 直接进入返回共享引用的迭代器,而不首先将其转换为引用。有一种兄弟方法 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天全站免登陆