gpt4 book ai didi

rust - 查看 `for` 循环内的迭代器

转载 作者:行者123 更新时间:2023-12-05 08:45:27 28 4
gpt4 key购买 nike

我试图在遍历 &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;

知道这里发生了什么吗?我尝试了引用和取消引用的各种组合,但我尝试过的似乎都不起作用。

最佳答案

迭代器被移动到 for 循环中。您不能在 for 循环内手动操作迭代器。但是,for 循环可以替换为 while let:

while let Some(c) = iter.next() {
let current: char = c;
let next: char = *iter.peek().unwrap_or(&'∅');
}

Playground .

关于rust - 查看 `for` 循环内的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72787359/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com