External Publication
Visit Post

[Pre-RFC] Peeking from Peekable with less unwrapping

Rust Internals [Unofficial] May 8, 2026
Source

Your code is unsound. You have to forbid keeping the reference returned by get when consume is called:

    let mut it = vec![String::from("hello")].into_iter().peekable();
    let p = Peeked::peek_from(&mut it).unwrap();
    let r: &String = p.get();
    let owned: String = p.consume(); // moves the String
    drop(owned);
    println!("{r}"); // r is a stale reference

Discussion in the ATmosphere

Loading comments...