How to use Iterator scan and inspect

Use inspect to observe iterator items and scan to maintain state across iterations in Rust.

Use inspect to observe values during iteration without changing them, and scan to maintain state across iterations by returning a new value for each step.

let numbers = vec![1, 2, 3, 4];

// inspect: prints each item without modifying the stream
numbers.iter().inspect(|n| println!("Inspecting: {}", n)).count();

// scan: accumulates a running total starting from 0
let sum: Vec<i32> = numbers.iter()
    .scan(0, |state, &n| {
        *state += n;
        Some(*state)
    })
    .collect();

println!("Running sums: {:?}", sum); // [1, 3, 6, 10]