迭代器是否在Rust中返回对项目的引用或项目的值? [英] Do iterators return a reference to items or the value of the items in Rust?

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

问题描述

如果我有矢量:

let mut v = vec![0, 1, 2, 3, 4, 5];

我遍历它:

for &item in v.iter() {}

这里& item 是引用还是值?看来这可能是& 部分的参考,但是阅读详细信息似乎表明这是一个价值.

Would &item here be a reference or a value? It seems like it would be a reference from the & part, but reading the details seem to show it's a value???

推荐答案

迭代器是否在Rust中返回对项目的引用或项目的值?

Do iterators return a reference to items or the value of the items in Rust?

这个问题没有普遍的答案.迭代器可以返回任何一个.您可以通过在文档中查找关联的类型 Iterator :: Item 来找到项目的类型.例如, Vec :: iter()的文档告诉您返回类型为

There's no general answer to this question. An iterator can return either. You can find the type of the items by looking up the associated type Iterator::Item in the documentation. The documentation of Vec::iter(), for example, tells you that the return type is std::slice::Iter. The documentation of Iter in turn has a list of the traits the type implements, and the Iterator trait is one of them. If you expand the documentation, you can see

type Item = &'a T

告诉您,迭代器的项目类型由& T 返回,即 Vec< T> :: iter()向量本身的类型.

which tells you that the item type for the iterator return by Vec<T>::iter() it &T, i.e. you get references to the item type of the vector itself.

表示法

for &item in v.iter() {}

for 之后的部分是与迭代器中的项目匹配的 pattern .在第一次迭代中,& item & 0 匹配,因此 item 变为 0 .您可以在任何Rust简介中阅读有关模式匹配的更多信息.

the part after for is a pattern that is matched against the items in the iterator. In the first iteration &item is matched against &0, so item becomes 0. You can read more about pattern matching in any Rust introduction.

另一种遍历向量 v 的方法是编写

Another way to iterate over the vector v is to write

for item in v {}

这将消耗向量,因此在循环后将无法再使用它.所有项目均从向量中移出并按值返回.这使用为 Vec< T> 实现的 IntoIterator 特性,因此在文档中查找它的项类型!

This will consume the vector, so it can't be used anymore after the loop. All items are moved out of the vector and returned by value. This uses the IntoIterator trait implemented for Vec<T>, so look it up in the documentation to find its item type!

上面的第一个循环通常写为

The first loop above is usually written as

for &item in &v {}

借用 v 作为参考& Vec< i32> ,然后在该参考上调用 IntoIterator ,这将返回相同的结果上面提到的 Iter 类型,因此它也会产生引用.

which borrows v as a reference &Vec<i32>, and then calls IntoIterator on that reference, which will return the same Iter type mentioned above, so it will also yield references.

这篇关于迭代器是否在Rust中返回对项目的引用或项目的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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