std-method

Iterator::scan — accumulate state while yielding

Maintain state between calls and optionally yield an output per step. Unlike fold, scan can yield intermediate results; a None stops normal traversal, but is not a permanent-exhaustion guarantee. Expected stdout (not executed): [4, 2, 9] Common mistake: Using fold when intermediate totals are needed.

Formal Syntax & Structure

rust syntaxrust
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>

Working Example

Example Snippetrust
fn main() {    let balances: Vec<_> = [4, -2, 7].into_iter().scan(0, |total, n| { *total += n; Some(*total) }).collect();    println!("{balances:?}");}
Rust Reference