In Rust, how does `Iterator::try_fold` stop a checked total at the first overflow, and why do std's adapters override `try_fold` and `fold`?
answer
- fallible accumulator
- Option, Result or ControlFlow
- takes &mut self, resumable
- internal iteration inside adapters
basics
~20 stry_fold threads an accumulator through a closure returning Option, Result or ControlFlow; the first None, Err or Break is returned at once and the rest stays unread. Adapters override it so work can loop inside each inner iterator.
solid answer
~40 s`try_fold(init, f)` is `fold` with an exit: `f` returns a type like `Option<B>`, `Result<B, E>` or `ControlFlow<X, B>`, and the first `None`, `Err` or `Break` is returned immediately. So `it.try_fold(0u32, |acc, &b| acc.checked_add(b))` gives `Some(total)` or `None` at the first overflow, and because `try_fold` takes `&mut self`, the remaining items are still in `it`. std builds `any`, `find` and friends on `try_fold`, and `for_each` and `count` on `fold`. That is why adapters such as `Chain`, `Map` and `Flatten` override both: `Chain::try_fold` runs the first iterator's own `try_fold` loop and then the second's, instead of re-checking which half is active on every `next()` call. Internal iteration like this can optimise better than a `for` loop over the same chain — but measure, because in many cases both compile to the same code.
code
rust · 19 linesuse std::ops::ControlFlow;
fn main() {
// bytes served per request, parsed from an access log
let bytes: [u32; 5] = [4_000_000_000, 200_000_000, 300_000_000, 10, 20];
let mut it = bytes.iter();
let total = it.try_fold(0u32, |acc, &b| acc.checked_add(b));
println!("{total:?}"); // None: the third add overflows u32
println!("left: {:?}", it.as_slice()); // [10, 20]: never pulled
// Break carries the index of the request that crossed the budget
const BUDGET: u64 = 4_100_000_000;
let crossed = bytes.iter().enumerate().try_fold(0u64, |acc, (i, &b)| {
let next = acc + u64::from(b);
if next > BUDGET { ControlFlow::Break(i) } else { ControlFlow::Continue(next) }
});
println!("{crossed:?}"); // Break(1)
}go deeper
Recall that try_fold is fold with an exit: a None or Err from the closure stops the loop and is returned.
Explain the Option, Result and ControlFlow return types, checked_add as the classic use, and that try_fold borrows the iterator so the rest can be resumed.
Use try_fold for overflow-safe totals and early exits that report where they stopped, and explain internal versus external iteration as the reason adapters override fold and try_fold.
Treat iterator-versus-loop performance claims as hypotheses: require release-build benchmarks before style rewrites, and prefer clarity where the measured difference is noise.
## The signature ```rust fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R where F: FnMut(B, Self::Item) -> R, R: Try<Output = B>, ``` Three details matter: - **`R: Try<Output = B>`** — the closure returns a "try" type whose success value is the next accumulator. On stable Rust that means `Option<B>`, `Result<B, E>` or `std::ops::ControlFlow<X, B>`. The `Try` trait itself is unstable, so you use these types rather than implementing it for your own. - **Short-circuiting** — std's default body is a loop that applies `?` to each closure result. The first `None`, `Err(e)` or `ControlFlow::Break(x)` is returned at once. - **`&mut self`** — unlike `fold`, it borrows the iterator. After an early stop, the items not yet pulled are still there. std's own documentation demonstrates this: after an `i8` overflow on `100`, `iter.next()` still returns `Some(40)`. ## An overflow-safe total A log analyser totals bytes served per request. With `u32` and large responses, a plain `sum::<u32>()` would panic in debug or wrap in release. `try_fold` with `checked_add` turns overflow into a value: ```rust let total = it.try_fold(0u32, |acc, &b| acc.checked_add(b)); // Some(total), or None at the first overflowing add ``` `checked_add` returns `None` on overflow, so the `None` short-circuits. Contrast `fold` with an `Option` accumulator: it would keep calling the closure on every remaining item, propagating `None` by hand, with no early exit. ## `ControlFlow` when the stop carries a value You cannot `break` out of a closure, but `ControlFlow` gives the same effect with a payload. `ControlFlow::Continue(acc)` keeps going; `ControlFlow::Break(x)` stops and returns `Break(x)`. In the example below, `Break` carries the index of the request that pushed the running total over a byte budget, while `Continue` carries the total itself — two different types, which `Option` could not express. ## Why adapters override `try_fold` and `fold` There are two ways to drive an iterator: 1. **External iteration** — the caller calls `next()` in a loop. A `for` loop does this. 2. **Internal iteration** — the caller hands a closure to the iterator, and the iterator runs the loop itself. `fold`, `try_fold`, and everything built on them (`for_each`, `count`, `sum`, `any`, `all`, `find`, `position`) do this. For a simple slice iterator the two are equivalent. For composite adapters they are not. `Chain::next` must check, on every call, whether the first iterator is still active. `Chain::try_fold`, as std implements it, instead calls the first iterator's own `try_fold` to completion, then the second's — two tight loops with no per-item state check. `Flatten` and `FlatMap` do the same for each inner iterator, and `Map` forwards `try_fold` to its source with the mapping folded into the closure. std's documentation for `try_fold` tells implementers this directly: several forward methods have default implementations in terms of it, so implement it explicitly if it can do something better than the default loop, ideally by calling `try_fold` on the internal parts. That is why `a.chain(b).for_each(f)` can optimise better than `for x in a.chain(b) { f(x) }`. ## The zero-cost claim and its limits The Book describes iterators as a zero-cost abstraction and says that in many cases iterator code compiles to the same assembly as a hand-written loop, with bounds checks removed and loops unrolled. Read the scope carefully: - "in many cases" is not "always"; adapter-heavy chains driven by `next()` are where differences show up; - the gain from internal iteration is an optimisation opportunity, not a guarantee; - only a benchmark of release builds, on your data, settles a rewrite. ## Review checklist - A running total that may overflow uses `try_fold` with `checked_add`, or a wider type, not a bare `sum`. - An early exit that must report *where* it stopped uses `ControlFlow::Break` with the index or item. - Code that resumes after an early stop relies on `try_fold`'s `&mut self` — make sure the iterator is not moved into the call. - A hot loop over `chain` or `flatten` is a candidate for `for_each` or `try_for_each` — after measuring. - A custom iterator wrapping several inner iterators should forward `fold` and `try_fold` to them for the same reason (writing that impl is covered with custom sequence types). - A stream that must report every failure, not just the first, should not use `try_fold` at all: it stops at the first `None` or `Err` by design, so collect the errors with a plain `fold` or loop instead.
- Why can `a.chain(b).for_each(f)` run faster than `for x in a.chain(b) { f(x) }`?The `for` loop drives the chain externally, so every item goes through `Chain::next`, which checks which half is active. `for_each` is built on `fold`, and `Chain::fold` runs `a`'s own fold and then `b`'s, two plain loops with no per-item check. The optimiser often removes the difference anyway, so benchmark a release build before rewriting.
- Can you implement `Try` for your own enum so `try_fold` short-circuits on it?Not on stable Rust: the `Try` trait is unstable. Use the stable types that already implement it — `Option`, `Result`, or `std::ops::ControlFlow`, which lets the break value and the continue value have different types. Convert your own enum into one of those inside the closure.
- What is the difference between `try_fold` and `try_for_each`?`try_for_each` is the stateless form: its closure takes only the item and returns a try type with `()` as the success value, such as `Result<(), E>`. It stops at the first failure and returns it. Use `try_fold` when an accumulator must be threaded through; use `try_for_each` for fallible side effects, such as writing each line.
- try_fold consumes the iterator, so nothing is left after an early stop
- fold with an Option accumulator stops at the first None just like try_fold
- Iterator chains always compile to exactly the code of a hand-written loop
- You must implement the Try trait yourself to short-circuit with a custom value
- Adapters override try_fold only for readability, not for code generation