Consuming Iterators
Consumption runs the pipeline: for, collect, sum, count, fold, reduce, last, any, all.
Recipe
fn main() {
let total: i32 = (1..=5).sum();
let evens: Vec<_> = (0..10).filter(|n| n % 2 == 0).collect();
println!("{total} {:?}", evens);
}When to reach for this: Final step after adapters - pick consumer matching output need.
Working Example
fn stats(nums: impl IntoIterator<Item = f64>) -> (f64, f64) {
let mut count = 0u64;
let sum: f64 = nums.into_iter().inspect(|_| count += 1).sum();
(sum, sum / count as f64)
}
fn main() {
println!("{:?}", stats([1.0, 2.0, 3.0]));
}What this demonstrates:
sumconsumerinspectside effect countingIntoIteratorflexible input
Deep Dive
collect builds many types via FromIterator. fold is general reducer. for desugars to while let Some.
Gotchas
- collect without type hint - Ambiguous. Fix:
collect::<Vec<_>>(). - sum on empty - Returns zero for numeric types - know identity.
- reduce on empty - Returns
None. Fix:foldwith seed. - for mutates while iterating adapter - Borrow rules on source.
- needless collect - clippy flags extra allocations.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
try_for_each | Fallible each step | Need collected vec |
| Manual loop | Break/continue complex | Simple sum |
fold | Single accumulator | Built-in sum works |
FAQs
collect to String?
join after collect chars or write!.partition?
split into two vecs by predicate.unzip?
Pair of vecs from (A,B) items.count?
Consumes full iterator.last?
Needs full scan.max?
Requires Ord on Item.for borrow?
for x in &collection.extend?
vec.extend(iter).from_iter?
Collect alias.benchmark?
Compare collect vs manual.Related
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.