External Publication
Visit Post

[Pre-RFC] Peeking from Peekable with less unwrapping

Rust Internals [Unofficial] April 13, 2026
Source

You can implement this without unwrap by comparing the Options a.peek() and b.peek() to decide which of the iterators to return the value of next() from. (Note that you will need to use a comparison that sorts Some before None and low Some before high Some, which I don't think is built-in in Option, but it is easy enough to implement.) This avoids unwrapping because all you're doing is deciding which iterator to iterate on, and if you're taking a value from an empty iterator it is because both are exhausted, so you can return the None you get directly.

I'm not sure whether or not this technique generalises, but it is at least pretty good for iterator adaptors (and might generate simpler code than you get with Peeked).

Discussion in the ATmosphere

Loading comments...