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)
Vec不实现Iteratortrait的设计原因是什么?
它应该实现三个迭代器中的哪一个?您可以从 a 获得三种不同类型的迭代器Vec:
vec.iter()给Iterator<Item = &T>,vec.iter_mut()给出Iterator<Item = &mut T>并修改向量和vec.into_iter()Iterator<Item = T>在这个过程中给出和消耗向量。与 Scala 相比:
在 Scala 中它也不Iterator直接实现,因为Iterator需要向量本身没有的下一项指针。然而,由于 Scala 没有移动语义,它只有一种从向量创建迭代器的方法,所以它可以隐式地进行转换。Rust 有三种方法,所以它必须问你想要哪一种。
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |