Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peek iterator inside `for` loop

I'm trying to peek at the char in-front of my current location whilst iterating over a &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(&'∅');
}

I will be passing this char into a method down the line. However, even this MRE produces a borrow after move error that I'm not sure how to get past.

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;

Any idea what's going on here? I've tried various combinations of referencing and dereferencing but nothing I've tried seems to work.

like image 752
Persistence Avatar asked Oct 31 '25 07:10

Persistence


2 Answers

The iterator is moved into the for loop. You cannot manually manipulate an iterator inside a for loop. However, the for loop can be replaced by while let:

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

Playground.

like image 51
Chayim Friedman Avatar answered Nov 03 '25 09:11

Chayim Friedman


If you can work with slices, it will get much easier with 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];
}

Playground

like image 39
Kaplan Avatar answered Nov 03 '25 10:11

Kaplan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!