Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator scan, inspect and fuse

Reference for the stateful and debugging iterator adapters scan, inspect and fuse in Rust: running totals, tracing pipelines and what happens after None.

Three small adapters cover jobs the bigger ones do not. scan is like map with a private piece of state that survives from one item to the next, which makes running totals and similar sequences easy. inspect lets you look at each item as it passes by without changing it, which is what you want when debugging a long chain. fuse guarantees that once an iterator returns None, it keeps returning None.

All three are lazy: nothing happens until something consumes the iterator.

Rust
let running: Vec<i32> = [1, 2, 3, 4]
    .iter()
    .scan(0, |sum, &x| { *sum += x; Some(*sum) })
    .collect(); // [1, 3, 6, 10]

Try it

Rust Running totals with scan

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Tracing a pipeline with inspect, and fuse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
    where F: FnMut(&mut St, Self::Item) -> Option<B>;
fn inspect<F>(self, f: F) -> Inspect<Self, F>
    where F: FnMut(&Self::Item);
fn fuse(self) -> Fuse<Self>;
Name Description
initial_state Starting value of the private state handed to the closure as &mut St.
f (scan) Receives the state and the item; returns Some(output) to yield a value, or None to end the iteration.
f (inspect) Receives a reference to each item; its return value is ().

Returns: a new adapter iterator. Scan yields the B values; Inspect yields the original items; Fuse yields the original items.

Errors / panics / edge cases: nothing panics. A scan closure that returns None stops the whole iterator permanently, even if the source still has items.

Usage notes

  • scan versus fold: fold returns only the final accumulator; scan emits a value for every step. If you need both, take .last() of a scan or run a fold separately.
  • State is mutable through a reference. Assign with *state = ... or use +=. The state cannot be borrowed out of the closure, so produce owned or Copy outputs.
  • scan can short-circuit, which map cannot do. It is a compact replacement for a loop with a running variable and a break.
  • inspect is for observation only. It borrows items immutably; use map if you want to change them. Leaving println! calls in inspect in production code is a common leftover.
  • inspect only runs for items that are actually pulled, so with take(2) you see only the items that reached inspect before the limit.
  • fuse rarely matters for standard-library iterators, because most of them are already fused (FusedIterator). It matters for hand-written iterators and for adapters like zip or chain fed by a source that may wake up after None.
  • Fuse cost: a flag per iterator; it is optimized away for types that implement FusedIterator.