Fuse An Iterator After It Returns None

Adapters behind an iterator can emit values after their first None; fuse() turns that first None into a permanent end so pipelines stay safe.

RustData Integrity

Code

rustsnippet
28 lines
// 一个违约的迭代器:第一次 None 之后还会吐值(协议不保证,但可能发生)
struct Flaky {
    state: u32,
}

impl Iterator for Flaky {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        self.state += 1;
        match self.state {
            1 => Some(10),
            2 => None,     // 第一次结束
            3 => Some(99), // 违约:结束后又冒出一个值
            _ => None,
        }
    }
}

fn main() {
    let mut raw = Flaky { state: 0 };
    println!("{:?} {:?} {:?}", raw.next(), raw.next(), raw.next());

    // fuse:第一个 None 之后永远返回 None
    let mut safe = Flaky { state: 0 }.fuse();
    println!("{:?} {:?} {:?}", safe.next(), safe.next(), safe.next());
    println!("still safe: {:?}", safe.next());
}

A contract-violating iterator

Flaky returns Some(10), then None, then Some(99) — values after the first None, which the Iterator contract does not guarantee against but adapters may still exhibit. The raw triple print shows 10, None, 99.

What fuse() changes

Wrapping with .fuse() makes the first None permanent: the safe iterator prints 10, None, None, and the follow-up still safe line confirms None again.

Where this matters

Pipelines that assume None means done (fold, collect, while-let loops) stay correct even when an adapter behind them misbehaves; fuse() is the explicit way to buy that guarantee.

Interactive Tools for This Topic

FAQ

What guarantee does fuse() add?
Once the fused iterator returns None it will keep returning None, even if the underlying iterator emits values later.
Why can values appear after None at all?
The Iterator trait does not forbid it; custom or adapter-wrapped iterators may emit again, which the Flaky struct demonstrates deliberately.