`map` / `filter` / `fold`
map transforms each item, filter keeps some items, and fold collapses the sequence to one value. Together they are the core iterator pipeline.
Detailed Explanation
map applies a function to every item and yields the results. It is the same length as the input (unless you map to Option and then flatten). filter applies a predicate and yields the items for which it is true. filter_map combines both: the function returns Option<U> and None is dropped. Prefer filter_map over map(...).flatten() on options.
fold is the universal reducer: iter.fold(init, |acc, x| acc + x). The accumulator is the first argument and the function returns the next accumulator. reduce is fold without an init, using the first item, and returns Option so an empty iterator is None. sum and product are specialised folds. for_each is a fold that returns ().
These three are the functional core. Almost every other adapter is a map, a filter, a fold, or a combination. any is a fold that stops early. collect is a fold into a collection via FromIterator. Understanding that helps you rewrite a clumsy pipeline: if the end is one value, you want a fold, not a collect plus an index loop.
Order matters for cost. filter then map skips the map work for discarded items. map then filter computes values you throw away. take at the end of a filter still stops early because iterators are pull-based: take stops asking next of the filter, which stops asking next of the source.
fold can be harder to read than a for loop when the accumulator is a struct you mutate. That is fine. Write the loop. fold shines when the accumulator is a simple value or when you are in a chain already.
When you write map/filter: a pipeline that stays an iterator. When you write fold: one result, especially a number or a small struct. When you write for: the body is statements, not an expression.
Code Examples
fn main() {
let xs = [1, 2, 3, 4];
let doubled: Vec<_> = xs.iter().map(|x| x * 2).collect();
println!("{doubled:?}"); // prints: [2, 4, 6, 8]
let even_sum = xs.iter().filter(|x| *x % 2 == 0).fold(0, |acc, x| acc + x);
println!("{even_sum}"); // prints: 6
let first_even = xs.iter().copied().filter_map(|x| (x % 2 == 0).then_some(x)).next();
println!("{first_even:?}"); // prints: Some(2)
}Common Gotchas
`filter` yields the original item
The predicate sees `&Item`. `filter_map` is how you change the type and drop in one step.
`fold` on a `Vec` as accumulator can hide quadratic copies
If the accumulator is a `String` and you write `acc + x`, you copy every time. `for` plus `push_str`, or `fold` with `&mut String` via `for_each`.
`reduce` is empty-safe
It returns `Option`. `fold(0, ...)` on an empty iterator returns `0`, which may or may not be what you want.
Side effects in `map` surprise readers
A `map` that prints or writes is a `for_each`. Keep `map` pure.