ScottishTapWater
ScottishTapWater

Reputation: 4806

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.

Upvotes: 4

Views: 1102

Answers (2)

Kaplan
Kaplan

Reputation: 3728

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

Upvotes: 3

Chayim Friedman
Chayim Friedman

Reputation: 70970

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.

Upvotes: 12

Related Questions