Sub topic 11
Consumers: sum, fold, count, find, any, all
This chapter assumes you know ownership and borrowing, generics with trait bounds, Option, and how iter() and adapters like map and filter work. Adapters build a pipeline but do no work. A consumer is an Iterator method that calls next repeatedly and produces a final value, which is what starts the pipeline running.
Consumers take the iterator
Every consumer here takes self by value or by &mut self. After a by-value consumer such as sum, count or fold, the iterator is gone and you cannot use it again. The short-circuiting consumers (find, any, all) take &mut self, so the iterator can be used again afterwards, and it resumes after the last item they looked at.
| Consumer | Returns | Stops early? |
|---|---|---|
| `sum`, `product` | A number type you name | No |
| `count` | `usize` | No |
| `fold` | Your accumulator type | No |
| `find` | `Option<Item>` | Yes, at the first match |
| `any` | `bool` | Yes, at the first `true` |
| `all` | `bool` | Yes, at the first `false` |
sum, count and fold
sum needs to know the result type, because many types implement Sum. Annotate the variable or use turbofish (sum::<i32>()). count returns how many items remain.
fold is the general tool. It takes a starting value and a closure |acc, item| new_acc. The closure runs once per item and each result becomes the next acc. sum and count are special cases of it.
fn main() {
let v = vec![3, 8, 1, 9, 4];
let total: i32 = v.iter().sum();
let big = v.iter().filter(|&&n| n > 3).count();
let longest_run = v.iter().fold(String::new(), |mut acc, n| {
if !acc.is_empty() {
acc.push('-');
}
acc.push_str(&n.to_string());
acc
});
println!("{}", total); // 25
println!("{}", big); // 3
println!("{}", longest_run); // 3-8-1-9-4
}The accumulator type does not have to match the item type. Here the items are &i32 and the accumulator is a String.
find, any and all
These three stop as soon as the answer is known. find takes a closure that receives a reference to the item, so with iter() you often see &&i32 patterns. any and all receive the item itself.
fn main() {
let v = vec![3, 8, 1, 9, 4];
let first_even = v.iter().find(|&&n| n % 2 == 0);
let has_nine = v.iter().any(|&n| n == 9);
let all_positive = v.iter().all(|&n| n > 0);
println!("{:?}", first_even); // Some(8)
println!("{}", has_nine); // true
println!("{}", all_positive); // true
}On an empty iterator, any returns false and all returns true. The second result surprises people, so check for emptiness separately if it matters.
Overflow in sum
sum on integers panics on overflow in debug builds and wraps in release builds. If the total can be large, widen the type first, for example map(|&n| n as i64).sum::<i64>().
Exercise
Write a function fn all_short_and_count(words: &[&str]) -> (bool, usize) that returns whether every word has fewer than 6 characters, and how many words start with the letter 'a'. Why can't you do both with a single iterator value?
Show answer
Use two pipelines: let all_short = words.iter().all(|w| w.len() < 6); and let a_count = words.iter().filter(|w| w.starts_with('a')).count();, then return (all_short, a_count). count takes the iterator by value, so it is consumed. all borrows it mutably and may stop early, so it leaves the iterator partly used. Calling words.iter() again creates a fresh iterator for each pass.