我有一个简单的程序如下:
let x = vec![1,2,3];
let iterator = x.iter();
for z in iterator {}
for z in iterator {}正如我们所知,x.iter()是对x中值的引用,但是为什么我不能多次迭代迭代器呢?它给出了以下错误(游乐场):
error[E0382]: use of moved value: `iterator`
--> src/main.rs:5:14
|
3 | let iterator = x.iter();
| -------- move occurs because `iterator` has type `std::slice::Iter<'_, i32>`, which does not implement the `Copy` trait
4 | for z in iterator {}
| -------- `iterator` moved due to this implicit call to `.into_iter()`
5 | for z in iterator {}
| ^^^^^^^^ value used here after move
|
note: this function takes ownership of the receiver `self`, which moves `iterator`这个问题在(&x).into_iter()中也存在,我不能多次迭代它。
发布于 2022-06-08 02:22:47
迭代器是有状态的。迭代器正在物理上改变自己,以便在数据循环过程中循环。在第一个for循环的末尾,即使您拥有它的所有权(因为for循环剥夺了您的所有权),它也是一个指向列表末尾的无用迭代器(在C++术语中,只有一个结束),并且无法访问实际的数据。迭代器的意义在于它有状态地遍历数据结构,因此要使用它,就必须使用它。
这不仅在Rust中是正确的,在大多数有迭代器概念的语言中也是如此。“可迭代”或“可枚举”数据结构(如列表或数组)通常可多次迭代,但作为一个概念的“迭代器”是进行迭代工作的东西,它只工作一次。这允许Rust (和其他语言)使用延迟迭代器来实现像.map和.filter这样的东西,并且还可以在无限数据结构上迭代。
https://stackoverflow.com/questions/72539362
复制相似问题