【发布时间】:2022-01-27 07:54:30
【问题描述】:
我正在 rust 中测试一个自定义的双向迭代器,但我遇到了错误
error[E0382]: borrow of moved value: `iter`
--> src/main.rs:40:13
|
37 | let mut iter = BiIterator::from(vec![1, 2, 3]);
| -------- move occurs because `iter` has type `BiIterator<i32>`, which does not implement the `Copy` trait
38 | for i in iter {
| ----
| |
| `iter` moved due to this implicit call to `.into_iter()`
| help: consider borrowing to avoid moving into the for loop: `&iter`
39 | if i == 3 {
40 | iter.position(0);
| ^^^^^^^^^^^^^^^^ value borrowed here after move
|
note: this function takes ownership of the receiver `self`, which moves `iter`
【问题讨论】:
-
您的链接不提供sn-p。除此之外,编译器似乎提供了您需要的所有信息。
-
要在操场上发布指向您的代码的链接,您需要单击“共享”按钮。否则你会得到一个空旷游乐场的链接……
-
添加了嵌入代码
-
@Masklinn 我该如何解决这个问题?
-
@Masklinn 编译器正确识别问题,但没有提供如何修复它的提示。它提供的使用
for i in &iter的建议没有用,因为它无法编译(因为&iter不可迭代),并且无论如何都不允许在循环内调用position()。对于有 Rust 经验的人来说,正确的解决方案是显而易见的,但对于初学者来说并非如此。
标签: for-loop rust iterator iteration move-semantics