Sub topic 11
Consumers: sum, fold, count, find, any, all
This chapter assumes you can read closure syntax and know how iter(), iter_mut() and into_iter() differ. It also assumes you know that adapters such as map and filter are lazy. Here we cover the methods that end a pipeline and produce a value.
What a consumer is
A consumer is an Iterator method that calls next repeatedly and produces a final result, not another iterator. Nothing in a lazy chain runs until a consumer drives it.
Most consumers take self by value, so the iterator is moved and cannot be used afterwards. A few take &mut self, so the iterator can be reused after they return. The difference matters in the section on partial consumption below.
| Method | Returns | Stops early? | Result on an empty iterator |
|---|---|---|---|
| `sum` | the summed type | no | zero |
| `product` | the product type | no | one |
| `count` | `usize` | no | `0` |
| `fold` | the accumulator type | no | the initial value |
| `find` | `Option<Item>` | yes | `None` |
| `position` | `Option<usize>` | yes | `None` |
| `any` | `bool` | yes | `false` |
| `all` | `bool` | yes | `true` |
sum, product and count
sum and product are generic over their return type. The compiler cannot guess it, so you must annotate it, either on the variable or with a turbofish such as sum::<i32>().
fn main() {
let v = vec![1, 2, 3, 4];
let total: i32 = v.iter().sum();
let product = v.iter().product::<i32>();
let evens = v.iter().filter(|&&x| x % 2 == 0).count();
println!("{total} {product} {evens}"); // 10 24 2
}v.iter() yields &i32. The standard library implements Sum<&i32> for i32, so you do not need copied() first. The filter closure receives &&i32, a reference to the item, which is why the pattern is |&&x|.
count consumes the whole iterator, even for adapters that could in principle know their length, so it is O(n) for most chains. If you only need the length of a slice or Vec, call len() instead.
fold
fold is the general-purpose consumer. It takes an initial accumulator and a closure |acc, item| new_acc. Each call returns the next accumulator, and the last one is the result. Many other consumers, including sum and count, could be written with fold.
fn main() {
let words = ["apple", "bob", "cat"];
let longest = words
.iter()
.fold("", |best, w| if w.len() > best.len() { *w } else { best });
println!("{longest}"); // apple
let data = [4, -2, 9, 0];
let (lo, hi) = data
.iter()
.fold((i32::MAX, i32::MIN), |(lo, hi), &x| (lo.min(x), hi.max(x)));
println!("{lo} {hi}"); // -2 9
}The accumulator can be any type, including a tuple, so one pass can compute several values. The initial value fixes the accumulator type. In the first example it is &str, so both branches of the if must also be &str. That is why the code writes *w: w is &&str.
Floats and fold
f64 does not implement Ord, so max() and min() are not available on an iterator of floats. Use fold with f64::max instead:
fn main() {
let readings = [2.5_f64, 9.75, -1.0];
let highest = readings.iter().copied().fold(f64::NEG_INFINITY, f64::max);
println!("{highest}"); // 9.75
}sum and product do work on floats, but the result depends on the order of addition because of rounding.
find, position, any and all
These four consumers short-circuit. They stop calling next as soon as the answer is known.
fn main() {
let nums = [3, 8, 11, 14];
let first_even = nums.iter().find(|&&x| x % 2 == 0);
let index = nums.iter().position(|&x| x > 10);
let any_big = nums.iter().any(|&x| x > 13);
let all_positive = nums.iter().all(|&x| x > 0);
println!("{:?} {:?} {} {}", first_even, index, any_big, all_positive);
// Some(8) Some(2) true true
}The closure parameter types differ between the methods, and this is a common source of compile errors:
findpasses&Itemto its closure. Foriter()over integers that is&&i32.position,anyandallpassItemby value. Foriter()that is&i32.findreturnsOption<Item>, so here it returnsOption<&i32>, notOption<i32>. Add.copied()if you want an owned value.
You can see the short-circuiting by counting how many items the closure sees:
fn main() {
let mut checks = 0;
let found = (1..=100).find(|n| {
checks += 1;
n * n > 50
});
println!("{:?} after {} checks", found, checks); // Some(8) after 8 checks
}Only 8 of the 100 items were visited. The same applies to infinite iterators: (1..).find(...) terminates if a match exists, but (1..).sum::<u64>() never returns.
Partial consumption and by_ref
find, position, any and all take &mut self. After they return, the iterator sits just past the last item they examined, and you can keep using it.
fn main() {
let mut it = 1..=10;
let first = it.find(|n| n % 4 == 0);
let rest: Vec<i32> = it.collect();
println!("{:?} {:?}", first, rest); // Some(4) [5, 6, 7, 8, 9, 10]
}Methods that take self by value, such as sum, count and fold, would move it. To use one of them on only part of an iterator, borrow it with by_ref(), which returns &mut I. &mut I is itself an iterator, so the by-value method moves only the borrow. For example, it.by_ref().take(3).sum::<i32>() leaves it positioned after the third item.
Overflow and try_fold
In a debug build, sum panics on integer overflow. In a release build it wraps silently unless you enable overflow checks. When the input is untrusted, use try_fold, which stops as soon as the closure returns None (or an Err):
fn main() {
let bytes = [200u8, 50, 10];
let checked = bytes.iter().try_fold(0u8, |acc, &x| acc.checked_add(x));
println!("{:?}", checked); // None
}Here 200 + 50 = 250 succeeds, but adding 10 overflows u8, so the whole result is None. Like find, try_fold short-circuits.
Choosing a consumer
- Use
sum,productorcountwhen the name says exactly what you want. They are the most readable. - Use
anyorallfor yes/no questions. They are clearer thanfind(...).is_some(). - Use
findwhen you need the item, andpositionwhen you need the index. - Use
foldwhen the result is a custom combination, or when you need several values from one pass. - Use
try_foldwhen combining can fail.
Exercise
What do Vec::<i32>::new().iter().all(|&x| x > 0) and [1, 2, 3].iter().find(|&&x| x > 5) return? Why does the second closure use &&x while any(|&x| ...) on the same iterator uses &x?
Show answer
The first returns true, because all is vacuously true when no item fails the test. The second returns None, because no element exceeds 5. iter() yields &i32. find passes a reference to that item, so its closure receives &&i32. any passes the item itself, so its closure receives &i32.
Exercise
Using a single fold over [3, 7, 2, 9], compute both the sum and the count of elements, and then print the average as an f64. Write the call.
Show answer
let (sum, count) = [3, 7, 2, 9].iter().fold((0, 0), |(s, c), &x| (s + x, c + 1)); println!("{}", sum as f64 / count as f64); This prints 5.25. The tuple accumulator lets one pass compute both values, so the iterator is consumed only once.