Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator peekable, peek and next_if

Reference for Peekable in Rust: look one item ahead with peek, peek_mut, next_if and next_if_eq, with tokenizer examples, borrowing rules and gotchas.

peekable() wraps an iterator in a Peekable adapter that can show the next item without consuming it. This is the standard tool for hand-written parsers and tokenizers, where you must look at a character to decide what to do, but only take it if it belongs to the current token.

peek() returns Option<&Item>. The first call pulls one item from the underlying iterator and stores it; later calls return the stored item until next() takes it.

Rust
let mut it = [1, 2, 3].into_iter().peekable();
assert_eq!(it.peek(), Some(&1));
assert_eq!(it.next(), Some(1));

Try it

Rust Peek before consuming

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A tiny tokenizer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn peekable(self) -> Peekable<Self>;

impl<I: Iterator> Peekable<I> {
    fn peek(&mut self) -> Option<&I::Item>;
    fn peek_mut(&mut self) -> Option<&mut I::Item>;
    fn next_if(&mut self, func: impl FnOnce(&I::Item) -> bool) -> Option<I::Item>;
    fn next_if_eq<T>(&mut self, expected: &T) -> Option<I::Item>
        where T: ?Sized, I::Item: PartialEq<T>;
}
Name Description
func Test applied to a reference to the upcoming item.
expected Value compared with == against the upcoming item.

Returns: peek and peek_mut give an optional reference to the buffered item; next_if and next_if_eq give the item itself when it matched, otherwise None and the item stays buffered.

Errors / panics / edge cases: no panics. peek takes &mut self because it may need to advance the inner iterator, so you cannot hold the returned reference while calling next().

Usage notes

  • Why &mut: peeking fetches the item eagerly. Any side effects of the underlying iterator (reading a line, printing in inspect) happen at the time of the peek, not at the next().
  • Borrow trick: while let Some(&c) = it.peek() copies the character out so the borrow ends before it.next(). Without the & pattern the borrow checker rejects the loop body.
  • Passing it around: functions that parse from a peekable stream take &mut Peekable<I> or a generic I: Iterator<Item = char> wrapped as &mut Peekable<I>. The concrete name for a str is Peekable<Chars<'_>>.
  • One item only. There is no peek_n. For longer lookahead, collect into a Vec<char> and use an index, or wrap in a VecDeque buffer.
  • next_if and next_if_eq are stable since Rust 1.51 and replace the if cond { it.next(); } idiom.
  • Interaction with by_ref: a Peekable that was created from iter.by_ref() hands back the underlying iterator without the buffered item once dropped, so that peeked item is lost.
  • Cost: one Option<Option<Item>> of extra space; no allocation.