Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator fold, reduce and try_fold

Reference for Iterator::fold, reduce, try_fold, try_for_each and rfold in Rust: accumulating values, empty iterators, short-circuiting with Option and Result.

fold is the general-purpose accumulator: you give it a starting value and a closure that combines the accumulator with each item, and it returns the final accumulator. sum, product, count, max, any and collect can all be written with fold; reach for it when none of those fits.

reduce is fold without an initial value: the first item becomes the accumulator, so it returns an Option (None for an empty iterator). try_fold is fold that can stop early: the closure returns Option or Result (or ControlFlow) and the first None/Err ends the loop immediately.

Rust
let total = [1, 2, 3, 4].iter().fold(0, |acc, n| acc + n);   // 10
let best = [3, 9, 4].into_iter().reduce(i32::max);            // Some(9)

Try it

Rust fold and reduce

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 try_fold stops early

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 fold<B, F>(self, init: B, f: F) -> B
    where F: FnMut(B, Self::Item) -> B;

fn reduce<F>(self, f: F) -> Option<Self::Item>
    where F: FnMut(Self::Item, Self::Item) -> Self::Item;

fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
    where F: FnMut(B, Self::Item) -> R, R: Try<Output = B>;

fn try_for_each<F, R>(&mut self, f: F) -> R
    where F: FnMut(Self::Item) -> R, R: Try<Output = ()>;
Name Description
init The starting accumulator. Returned unchanged for an empty iterator.
f Receives the accumulator (by value) and the next item, returns the new accumulator.

Returns: fold returns the final accumulator; reduce returns Option<Item>; try_fold returns the same Try type as the closure (Option<B> or Result<B, E>): the final accumulator wrapped in Some/Ok, or the first None/Err.

Usage notes

  • The accumulator is moved in and out. That makes it cheap to build a String or Vec in a fold (as in the first example), because nothing is copied.
  • Order is left to right, so non-associative operations behave predictably. rfold runs from the right on double-ended iterators.
  • Prefer a named method when one exists: sum, product, max, min, any, all, count. They are clearer, and some are specialized for speed.
  • reduce needs matching types: the closure combines two items into one item. Use fold if the result type differs.
  • try_fold borrows (&mut self), so the iterator can be reused after an early exit; the remaining items are still there. Use it for checked arithmetic, parse-and-accumulate or any scan with a possible failure.
  • try_fold closures may return ControlFlow (Break(value) / Continue(acc)) to stop with a value that is not an error.
  • Overflow: a plain fold(0, |a, b| a + b) on integers panics on overflow in debug builds and wraps in release; use checked_add with try_fold or sum into a wider type.
  • Closures that mutate captured state are allowed (FnMut), but it is usually clearer to carry state in the accumulator.