在迭代&str时,我试图查看当前位置前面的字符。
let myStr = "12345";
let mut iter = myStr.chars().peekable();
for c in iter {
let current: char = c;
let next: char = *iter.peek().unwrap_or(&'∅');
}我将把这个字符向下传递到一个方法中。然而,即使这个MRE产生了一个在移动错误后的借用,我不知道如何通过。
error[E0382]: borrow of moved value: `iter`
--> src/lib.rs:7:27
|
4 | let mut iter = myStr.chars().peekable();
| -------- move occurs because `iter` has type `Peekable<Chars<'_>>`, which does not implement the `Copy` trait
5 | for c in iter {
| ---- `iter` moved due to this implicit call to `.into_iter()`
6 | let current: char = c;
7 | let next: char = *iter.peek().unwrap_or(&'∅');
| ^^^^^^^^^^^ value borrowed here after move
|
note: this function takes ownership of the receiver `self`, which moves `iter`
--> /home/james/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:267:18
|
267 | fn into_iter(self) -> Self::IntoIter;知道这是怎么回事吗?我尝试过引用和取消引用的各种组合,但我尝试过的任何东西似乎都没有效果。
发布于 2022-06-28 13:36:26
迭代器被移动到for循环中。您不能在for循环中手动操作迭代器。但是,for循环可以被while let替换。
while let Some(c) = iter.next() {
let current: char = c;
let next: char = *iter.peek().unwrap_or(&'∅');
}游乐场。
发布于 2022-06-28 18:38:39
如果您可以使用片,那么使用windows()将变得更加容易。
let slice = ['1', '2', '3', '4', '5'];
let iter = slice.windows(2);
for arr in iter {
let current = arr[0];
let next = arr[1];
}https://stackoverflow.com/questions/72787359
复制相似问题