简体   繁体   English

为什么 Vec 不实现 Iterator 特征?

[英]Why doesn't Vec implement the Iterator trait?

What is the design reason for Vec not implementing the Iterator trait? Vec没有实现Iterator特征的设计原因是什么? Having to always call iter() on all vectors and slices makes for longer lines of code.必须始终在所有向量和切片上调用iter()会导致代码行更长。

Example:例子:

let rx = xs.iter().zip(ys.iter());

compared to Scala:与 Scala 相比:

val rx = xs.zip(ys)

An iterator has an iteration state.一个迭代器有一个迭代 state。 It must know what will be the next element to give you.它必须知道下一个要给你的元素是什么。

So a vector by itself isn't an iterator, and the distinction is important.所以向量本身不是迭代器,区别很重要。 You can have two iterators over the same vector, for example, each with its specific iteration state.您可以在同一个向量上有两个迭代器,例如,每个迭代器都有其特定的迭代 state。

But a vector can provide you an iterator, that's why it implements IntoIterator , which lets you write this:但是向量可以为您提供一个迭代器,这就是它实现IntoIterator的原因,它可以让您编写以下代码:

let v = vec![1, 4];
for a in v {
    dbg!(a);
}

Many functions take an IntoIterator when an iterator is needed, and that's the case for zip , which is why许多函数在需要迭代器时采用IntoIterator ,这就是zip的情况,这就是为什么

let rx = xs.iter().zip(ys.iter());

can be replaced with可以替换为

let rx = xs.iter().zip(ys);

What is the design reason for Vec not implementing the Iterator trait? Vec没有实现Iterator特征的设计原因是什么?

Which of the three iterators should it implement?它应该实现三个迭代器中的哪一个? There are three different kinds of iterator you can get from a Vec :您可以从Vec获得三种不同类型的迭代器:

  1. vec.iter() gives Iterator<Item = &T> , vec.iter()给出Iterator<Item = &T>
  2. vec.iter_mut() gives Iterator<Item = &mut T> and modifies the vector and vec.iter_mut()给出Iterator<Item = &mut T>并修改向量和
  3. vec.into_iter() gives Iterator<Item = T> and consumes the vector in the process. vec.into_iter()给出Iterator<Item = T>并在过程中使用向量。

compared to Scala:与 Scala 相比:

In Scala it does not implement Iterator directly either, because Iterator needs the next item pointer that the vector itself does not have.在 Scala 中也没有直接实现Iterator ,因为Iterator需要向量本身没有的下一项指针。 However since Scala does not have move semantics, it only has one way to create an iterator from a vector, so it can do the conversion implicitly.然而,由于 Scala 没有移动语义,它只有一种从向量创建迭代器的方法,所以它可以隐式地进行转换。 Rust has three methods, so it must ask you which one you want. Rust有三种方法,所以一定要问你要哪一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM