sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-05 08:45:27 29 4
mua khóa gpt4 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>`, 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;

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

1 Câu trả lời

迭代器被移动到 循环中。您不能在 循环内手动操作迭代器。但是, 循环可以替换为 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/

29 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com