246. Iterator::peekable — Look at the Next Item Without Consuming It
Sometimes you need to see the next element to decide what to do — but calling .next() eats it. .peekable() gives you a .peek() that shows the next item while leaving it in place.
The problem: deciding based on what comes next
A classic case is joining items with a separator. You want a comma between elements but not a trailing one, so you need to know “is there another item after this?” A plain iterator can’t tell you without consuming it:
| |
peek() returns Option<&Item> — a reference to the next value if there is one — without advancing the iterator. The next .next() still hands you that same element.
The real power: peek to decide, then consume
Peeking shines when you’re parsing a stream and want to grab a run of elements that match a condition. Look at the front, and only call .next() once you’ve decided to keep it:
| |
The non-digit p stays in the iterator because we peeked at it instead of consuming it — the caller picks up exactly where the number ended.
next_if for the common case
When the pattern is “consume the next item only if it matches,” next_if does the peek-and-maybe-advance in one call:
| |
There’s also next_if_eq for the “advance past this exact value” case. Whenever you find yourself wishing you could un-call .next(), reach for .peekable().