Vec为什么不实现Iterator特性?

sge*_*sge 6 rust

Vec不实现该Iterator特性的设计原因是什么?必须始终调用iter()所有向量和切片将使代码行更长。

例:

let rx = xs.iter().zip(ys.iter());
Run Code Online (Sandbox Code Playgroud)

与Scala相比:

val rx = xs.zip(ys)
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 14

An iterator has an iteration 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.

But a vector can provide you an iterator, that's why it implements IntoIterator, which lets you write this:

let v = vec![1, 4];
for a in v {
    dbg!(a);
}
Run Code Online (Sandbox Code Playgroud)

Many functions take an IntoIterator when an iterator is needed, and that's the case for zip, which is why

let rx = xs.iter().zip(ys.iter());
Run Code Online (Sandbox Code Playgroud)

can be replaced with

let rx = xs.iter().zip(ys);
Run Code Online (Sandbox Code Playgroud)

  • @DenysSéguret因为在Rust中,`iter()`,`into_iter()`和`iter_mut()`之间的区别很重要。 (5认同)
  • @DenysSéguret你是对的。我想说的是,仅针对不可变的迭代启用它(使用`iter`),并且需要对`iter_mut`进行显式调用以实现可变的迭代。 (2认同)
  • 注意,可以在xs.iter()。zip(ys)中为ys设置相同的参数:如何选择使用ys.iter()或ys.iter_mut()? (2认同)
  • 对于`ys`,我们使用`into_iter`。原因很简单:使用了ys,因此其他迭代器类型没有意义。 (2认同)

Jan*_*dec 5

Vec不实现Iteratortrait的设计原因是什么?

它应该实现三个迭代器中的哪一个?您可以从 a 获得三种不同类型的迭代器Vec

  1. vec.iter()Iterator<Item = &T>,
  2. vec.iter_mut()给出Iterator<Item = &mut T>并修改向量和
  3. vec.into_iter()Iterator<Item = T>在这个过程中给出和消耗向量。

与 Scala 相比:

在 Scala 中它也不Iterator直接实现,因为Iterator需要向量本身没有的下一项指针。然而,由于 Scala 没有移动语义,它只有一种从向量创建迭代器的方法,所以它可以隐式地进行转换。Rust 有三种方法,所以它必须问你想要哪一种。

  • `into_iter()` 是消耗向量的函数;`drain` 的不同之处在于它仅“清空”向量。 (4认同)