The previous lesson ended every chain with collect, which builds a new vector. Often you do not want the items at all, only an answer about them: how many books are long, how many pages are left, whether anything is still pending. Collecting first and then asking the vector would allocate memory you throw away a line later. A consumer answers the question directly while the items stream past.
Consumers are the methods that take an iterator and pull items until they have an answer. count() returns how many items reach it. sum::<u64>() adds them up in the type you name. Both take the iterator by value, so it is used up afterward. That sounds limiting, but when the iterator only borrowed a collection, the collection is untouched, and a second question simply starts a new iterator.
Predict and run
The filter keeps pages of 100 or more. Which inputs count as long, and which inputs contribute to the sum?
fn main() {
let pages = [20_u32, 100, 120];
let long = pages.iter().filter(|page| **page >= 100).count();
let total = pages.iter().map(|page| u64::from(*page)).sum::<u64>();
println!("Long: {long}");
println!("Pages: {total}");
}Check your prediction
Long: 2
Pages: 240The comparison uses >=, so the boundary value 100 counts as long. The sum has no filter, so all three values contribute. The map widens each u32 to u64 before adding, which gives the total far more room than any single page count needs. Now try an empty array with let pages: [u32; 0] = [];. Predict both lines first: what is the count of nothing, and what is the sum of nothing?
An iterator is used up
Since a consumer takes the iterator by value, you cannot ask the same iterator twice. Storing a filtered chain in a variable and consuming it two times does not compile:
fn main() {
let pages = [20_u32, 100, 120];
let long = pages.iter().filter(|page| **page >= 100);
println!("Long: {}", long.count());
println!("Again: {}", long.count());
}The compiler reports error[E0382]: use of moved value: long. This is the ownership rule from the beginner course applied to an iterator: the first count() moved it. Building a fresh iterator is cheap, because it only holds a position in the array. When two queries share a long chain, put the chain in a closure that returns a new iterator each time it is called, as the worked solution below does.
Pick the consumer that matches the question
Different questions have different consumers, and several of them stop early. any returns true at the first match and never looks at the rest. find returns the first matching item. max and min return the largest or smallest item. The last three return an Option, because an empty input has no first or largest item.
fn main() {
let pages = [20_u32, 100, 120];
let none: [u32; 0] = [];
println!("Any over 110: {}", pages.iter().any(|page| *page > 110));
println!("First over 50: {:?}", pages.iter().find(|page| **page > 50));
println!("Longest: {:?}", pages.iter().max());
println!("Longest of none: {:?}", none.iter().max());
}Any over 110: true
First over 50: Some(100)
Longest: Some(120)
Longest of none: Nonefind returned 100, not 120: it stops at the first item that passes, in iteration order. max on an empty array gives None instead of inventing a value. count and sum never need an Option, because zero is a correct answer for an empty input.
The u64 widening in the predict example is not decoration. Overflow checks are on in this course's playgrounds, as in a debug build, so summing into a type that is too small stops the program:
fn main() {
let pages = [4_000_000_000_u32, 500_000_000];
let total: u32 = pages.iter().sum();
println!("{total}");
}That compiles but panics with attempt to add with overflow. In a release build without overflow checks, it would silently wrap to a wrong total instead. Choosing the result type is part of choosing the consumer.
Name the type the sum produces
sum can produce many numeric types, so Rust needs to know which one you want. Either annotate the variable, as in let total: u64 = ..., or use the turbofish, .sum::<u64>(). Pick a type wide enough for the largest total you expect, not just the largest single item.
Practice
Your turn
Write finished_stats for a slice of (pages, finished) pairs. Return the number of finished entries and the sum of their pages as a u64. For [(25, true), (100, false), (15, true)], it should print (2, 40). For an empty slice it should print (0, 0).
fn finished_stats(records: &[(u32, bool)]) -> (usize, u64) {
// Use one query for count and another for the page sum.
(0, 0)
}
fn main() {
let records = [(25, true), (100, false), (15, true)];
println!("{:?}", finished_stats(&records));
println!("{:?}", finished_stats(&[]));
}Hint 1: the idea
Both queries select the same records. Only the sum query needs to map each record to its pages, widened to u64.
Hint 2: a first step
Start each query with records.iter().filter(|record| record.1). Write it twice first; once it works, try moving it into a closure.
Worked solution
fn finished_stats(records: &[(u32, bool)]) -> (usize, u64) {
let finished = || records.iter().filter(|record| record.1);
let count = finished().count();
let pages = finished().map(|record| u64::from(record.0)).sum();
(count, pages)
}
fn main() {
let records = [(25, true), (100, false), (15, true)];
println!("{:?}", finished_stats(&records));
println!("{:?}", finished_stats(&[]));
}(2, 40)
(0, 0)The zero-argument closure finished, written || with nothing between the bars, returns a fresh iterator each time it is called, so the selection rule is written once and each consumer gets its own pass. It captures records by shared reference, as the closures in the last lesson captured limit, which is fine because nothing changes the slice while it is in use. sum needs no turbofish here because the function's return type already says the second value is a u64. The empty slice shows the identity values: a count of 0 and a sum of 0. The checkpoint next combines this with the ordered map from the first lesson.
Completion is saved in this browser only. It does not measure mastery.