112. Iterator::scan — Fold That Yields Every Step
fold keeps the running state but only hands you the final answer. So you reach for a mut variable plus map, or you give up and collect first. scan is the missing middle: a fold that yields each intermediate step.
The setup is familiar — you want a running total, not just the sum:
| |
It works, but the state lives outside the chain. map is supposed to be pure — leaning on a captured mut makes the iterator harder to refactor and impossible to compose.
scan puts the state inside the chain. You hand it an initial value and a closure that mutates the state and returns each yielded item:
| |
No captured state, no second pass. The closure returns Option<U>, so returning None ends the iteration early — handy for “stop when the running total crosses a threshold”:
| |
The state isn’t limited to numbers either — pair it with a tuple to track “previous + current” and you’ve got differences in one pass:
| |
Reach for scan whenever you’d otherwise write let mut acc = … outside a map. Same shape, no escapee state.