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.
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
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.
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
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
StringorVecin a fold (as in the first example), because nothing is copied. - Order is left to right, so non-associative operations behave predictably.
rfoldruns 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. reduceneeds matching types: the closure combines two items into one item. Usefoldif the result type differs.try_foldborrows (&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_foldclosures may returnControlFlow(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; usechecked_addwithtry_foldorsuminto a wider type. - Closures that mutate captured state are allowed (
FnMut), but it is usually clearer to carry state in the accumulator.
Related
sum, product, count,scan,min, max,any, all,Result::collect- Lessons: Iterators, Iterator patterns