External Publication
Visit Post

[Pre-RFC] Peeking from Peekable with less unwrapping

Rust Internals [Unofficial] April 13, 2026
Source

We have next_if and some other methods for conditional iteration over Peekable. The problem is that these methods are not really composable. Usually it is easier to use peek, do something with the peeked value and then do .next().unwrap(). This unwrap feels unnecessary and never fails if the value is already peeked and known to be there. Hence the following idea.

I propose to add a method for Peekable<I> with the following signature (the names here are temporary, of course):

fn peek_2(&'a mut self) -> Option<Peeked<'a, I>> { ... }

Peeked<'a, I> is a type with

fn get(&self) -> &'a I::Item { ... }
fn consume(self) -> I::Item { ... }

Calling the first method is equivalent to peek()ing. The second one equivalent to next(), but there is no unnecessary Option now.

I think the described interface cannot be implemented without using Peekable's internals or unsafe. Here is an implementation sketch with unsafe: Compiler Explorer. There is also an implementation of "merge iterator" using the proposed interface.

Discussion in the ATmosphere

Loading comments...