The Analogy: The Grading Table
Apples come up the line and a grader stands at the table. His instruction is simple: look at every apple, put the bruised ones in the bin at his feet, let the rest carry on. He works all shift, he touches all of them, and if you ask him at the start how many will get through he cannot tell you. The crate at the far end is whatever size it turns out to be.
A second grader has a different instruction, and it sounds almost the same. He has been told the load arrives heaviest first, so he is to stop the moment he sees an apple under weight -- everything from there on is undersized by definition and there is no point looking. On a properly sorted load he does the first grader's job in a fraction of the time. On a load that somebody tipped in unsorted he stops after four apples, and three hundred perfectly good ones roll past him untouched. He is not wrong. He did exactly what he was told. The instruction had a precondition, and the apples did not honour it.
A third grader is not sorting at all. His job is to read the little variety label on each apple and write the variety down, and some labels are smudged past reading. He is not doing two jobs -- deciding, and then reading -- he is doing one. The reading either produces a variety or it does not, and an apple whose label he could not make out simply never appears on his list. Splitting his work into "bin the unreadable ones, then read the rest" would mean reading every label twice.
The fourth was sent by the manager to fetch one Bramley for a photograph. He stops at the first one he sees. On a good day that is the second apple. The point is not that he is fast; the point is that he does not grade the whole load and then pick one out of the finished crate, and nobody would think to describe his job that way.
Syntax or Core Structure
filter takes a predicate and yields only the items it approves of:
fn main() {
let readings = vec![118, 0, 124, 7, 0, 131];
let live: Vec<i32> = readings.iter().copied().filter(|r| *r > 0).collect();
let big: Vec<i32> = readings.iter().copied().filter(|r| *r > 100).collect();
println!("{live:?}");
println!("{big:?}");
println!("live {} flat {}", live.len(), readings.len() - live.len());
let first_flat = readings.iter().find(|r| **r == 0);
let first_huge = readings.iter().find(|r| **r > 1000);
println!("{first_flat:?} {first_huge:?}");
}
Output:
[118, 124, 7, 131]
[118, 124, 131]
live 4 flat 2
Some(0) None
Look at the two predicates: one writes *r, the other writes **r, and both are correct. filter hands the predicate a reference to the item rather than the item itself, because it must not consume something it is about to yield. Its bound is FnMut(&Self::Item) -> bool. So the number of layers depends on what the item already was:
| Iterator built with | Item type | The predicate is handed | How the body reads it |
|---|---|---|---|
v.iter() | &i32 | a reference to a reference | two dereferences, or a double-reference pattern in the parameter |
v.iter().copied() | i32 | a reference to an i32 | one dereference, or a single-reference pattern |
v.into_iter() | i32 | a reference to an i32 | one dereference |
v.iter() with copied after the filter | &i32 at the filter | a reference to a reference | two dereferences, and the copy happens later |
This is the single most common reason a first filter refuses to compile, and it is oddly hard to spot because it never happens with structs -- field access and method calls dereference as many layers as they need to, so e.ok and s.parse() work at any depth. Comparison operators do not, so the moment your items are plain numbers the layers become visible.
find is the fourth grader. It is a consumer, not an adapter: it takes the same kind of predicate, stops at the first item that satisfies it, and returns Option of that item.
Technical Depth: Deciding And Transforming At Once
One closure instead of two passes
fn main() {
let rows = ["118", "n/a", "124", "", "131"];
let both: Vec<u32> = rows
.iter()
.filter(|s| s.parse::<u32>().is_ok())
.map(|s| s.parse::<u32>().unwrap())
.collect();
let once: Vec<u32> = rows.iter().filter_map(|s| s.parse::<u32>().ok()).collect();
println!("{both:?}");
println!("{once:?}");
let first = rows.iter().find_map(|s| s.parse::<u32>().ok());
println!("{first:?}");
}
Output:
[118, 124, 131]
[118, 124, 131]
Some(118)
Identical answers, and the top version is worse in three separate ways. It parses every row twice. It contains an unwrap whose safety depends entirely on the line above it, so a later edit that moves or loosens the filter turns a refactor into a panic. And it states the intent twice, which means the two statements can drift apart.
filter_map is the third grader: the closure returns Option, Some is kept and unwrapped for you, None is dropped, and the deciding and the converting are the same piece of work because they genuinely are. find_map is the same thing that stops at the first Some.
Testing everything versus stopping
fn main() {
let sorted = [131, 124, 118, 7, 0];
let jumbled = [7, 131, 124, 118, 0];
let a: Vec<i32> = sorted.iter().copied().take_while(|r| *r > 100).collect();
let b: Vec<i32> = jumbled.iter().copied().take_while(|r| *r > 100).collect();
let c: Vec<i32> = jumbled.iter().copied().filter(|r| *r > 100).collect();
let d: Vec<i32> = sorted.iter().copied().skip_while(|r| *r > 100).collect();
println!("take_while sorted {a:?}");
println!("take_while jumbled {b:?}");
println!("filter jumbled {c:?}");
println!("skip_while sorted {d:?}");
}
Output:
take_while sorted [131, 124, 118]
take_while jumbled []
filter jumbled [131, 124, 118]
skip_while sorted [7, 0]
The second line is the second grader going home. jumbled contains three items over 100 and take_while produced none of them, because the very first item failed and take_while never tests anything again. filter on the same data found all three.
| Adapter | Stops testing? | What comes out |
|---|---|---|
filter | No, it tests every item | Every item that passes, wherever it sits in the sequence |
take_while | Yes, at the first failure | The leading run that passes, then nothing at all |
skip_while | Yes, at the first failure | Everything from the first failure onwards, untested |
find | Yes, at the first success | Not an adapter -- a consumer returning Option |
skip_while has the mirror-image surprise: it skipped 131, 124 and 118, stopped testing at 7, and then yielded 7 and 0 without asking any further questions. It skips a leading run, not every matching item.
One more detail worth knowing before it bites: take_while has to pull the failing item in order to discover that it fails, and that item is then discarded. If the iterator is being shared through by_ref so that something else reads the rest of it, the boundary item is simply gone.
Both halves, and shrinking in place
fn main() {
let readings = [118, 0, 124, 7, 0, 131];
let (live, flat): (Vec<i32>, Vec<i32>) = readings.iter().copied().partition(|r| *r > 0);
println!("live {live:?}");
println!("flat {flat:?}");
let mut kept = readings.to_vec();
kept.retain(|r| *r > 0);
println!("kept {kept:?}");
}
Output:
live [118, 124, 7, 131]
flat [0, 0]
kept [118, 124, 7, 131]
partition is one walk producing two collections, which beats two filter passes with opposite predicates -- not only for speed but because opposite predicates written twice can fail to be opposites. Like collect, it needs to be told what the two halves are.
retain is the other shape of the same idea: it belongs to the collection rather than the iterator, it shortens the vector in place, and it allocates nothing. When you own the data and want it smaller, that is the tool; filter never changes its source.
Finally, the size hint. filter cannot know how many items will pass, so its lower bound is zero, and a collect downstream of it starts small and grows as it fills instead of reserving once. This is the case flagged in the previous lesson, and it is the price of not knowing.
Real World Example: Sifting One Log File Six Different Ways
Seven lines of text from a bay controller, one of them malformed, and six questions to answer about them:
#[derive(Clone)]
struct Entry {
at: &'static str,
bay: &'static str,
ok: bool,
units: u32,
}
fn parse(line: &'static str) -> Option<Entry> {
let mut parts = line.split(' ');
let at = parts.next()?;
let bay = parts.next()?;
let status = parts.next()?;
let units = parts.next()?.parse::<u32>().ok()?;
if parts.next().is_some() {
return None;
}
let ok = match status {
"ok" => true,
"fail" => false,
_ => return None,
};
Some(Entry { at, bay, ok, units })
}
fn main() {
let lines = [
"09:01 A1 ok 12",
"09:04 A2 fail 0",
"bad line",
"09:07 A1 ok 31",
"09:09 A3 fail 7",
"09:12 A1 ok 24",
"09:15 A2 ok 0",
];
let entries: Vec<Entry> = lines.iter().copied().filter_map(parse).collect();
println!("read {} of {}", entries.len(), lines.len());
let failures: Vec<&Entry> = entries.iter().filter(|e| !e.ok).collect();
println!("failures {}", failures.len());
for e in &failures {
println!(" {} {} {}", e.at, e.bay, e.units);
}
match entries.iter().find(|e| !e.ok) {
Some(e) => println!("first fail {} at {}", e.bay, e.at),
None => println!("first fail none"),
}
let (good, bad): (Vec<Entry>, Vec<Entry>) = entries.iter().cloned().partition(|e| e.ok);
println!("split {} good {} bad", good.len(), bad.len());
let a1_units: u32 = entries.iter().filter(|e| e.bay == "A1").map(|e| e.units).sum();
println!("A1 units {a1_units}");
let opening: Vec<&str> = entries.iter().take_while(|e| e.ok).map(|e| e.at).collect();
println!("clean run {opening:?}");
let busy: Vec<&str> = entries
.iter()
.filter_map(|e| if e.units > 20 { Some(e.bay) } else { None })
.collect();
println!("over 20 {busy:?}");
}
Output:
read 6 of 7
failures 2
09:04 A2 0
09:09 A3 7
first fail A2 at 09:04
split 4 good 2 bad
A1 units 67
clean run ["09:01"]
over 20 ["A1", "A1"]
The entire read is one line. filter_map(parse) turns seven strings into six entries, and "bad line" is not an error that has to be handled somewhere -- it is simply absent, which is either exactly right or exactly wrong depending on the program. Note that parse is passed by name with no closure around it, because its signature already is what filter_map asks for.
Then six questions and six different tools, and not one if inside a for loop among them. filter walks everything and answers "which ones". find stops at the first and answers "is there one, and which". partition answers "both halves, please" in a single pass. And the last filter_map answers "which ones, and give me one field of each" without a separate map step -- the if expression returning Option is the whole predicate and the whole projection at once.
clean run ["09:01"] is the interesting line, and it is in the example on purpose. Four of the six entries are ok, and take_while produced one of them. The second entry is a failure, so take_while stopped there and never looked again. That is not a defect: the question it answers is "how long did the clean opening run last", and the honest answer is one entry. If the question was "which entries succeeded", filter is the tool, and it is sitting three lines above returning four. Confusing these two is how a report quietly loses most of its rows.
The limits are real. Every field is &'static str, which works only because the lines are literals compiled into the program; read them from a file at runtime and you have Strings, so Entry must either own its text or carry a lifetime parameter tied to the buffer. The timestamps are strings, so they print and compare correctly but cannot be subtracted -- there is no duration anywhere in this program. parse reports nothing about why it rejected a line, which is precisely the trade filter_map makes; when you need that, the previous lesson's Vec<Result<_, _>> is the shape to reach for. There are six passes over the entries for six answers, which is the right call at six rows and worth folding together at six million. And partition clones every entry into one of two vectors; partitioning &Entry instead would copy nothing, at the cost of the halves not being able to outlive entries.
Common Mistakes
- Forgetting the extra reference layer.
v.iter().filter(|n| n > 10)does not compile, becausenis a reference to a reference to an integer and10is an integer. Write**n > 10, or destructure the parameter, or putcopied()in front of the filter.
- Being lulled by structs.
filter(|e| e.ok)works at any depth of reference because field access dereferences for you, so the layer problem stays invisible until the day your items are numbers. Knowing why the two cases differ is the only way to stop guessing at asterisks.
- Filtering and then mapping with the same fallible call.
filter(|s| s.parse::<u32>().is_ok()).map(|s| s.parse::<u32>().unwrap())does the work twice and hides anunwrapwhose safety lives in a different line.filter_mapwith.ok()is one call and nounwrap.
- Using
take_whilewhen you meantfilter. On data that happens to be sorted the two agree, which is the worst possible outcome, because the difference only appears later on real input and it appears as missing rows rather than as an error.
- Expecting
skip_whileto skip every match. It skips the leading run and then stops testing, so matching items after the first failure come straight through.
- Reinventing the consumers.
filter(..).next()isfind,filter(..).count() > 0isany, andfilter(..).next().is_some()is alsoany. The named versions stop early and say what you meant.
- Collecting in order to count.
filter(..).collect::<Vec<_>>().len()allocates a vector to produce one integer thatfilter(..).count()gives you for nothing.
- Expecting
filterto shrink the source. It builds a new sequence and leaves the original untouched.retainis the one that shortens aVecin place.
- Losing the boundary item.
take_whilepulls the item that fails the test and drops it, so on aby_refiterator that item never reaches whatever reads the remainder.
Best Practices
- Put
copied()orcloned()in front of the filter when the items are smallCopyvalues. One dereference in every predicate is easier to read than two, and the copy of an integer costs nothing.
- When one step both decides and converts, use
filter_map. The rule of thumb is that anyfilterwhose predicate calls a fallible function is afilter_mapwaiting to be written.
- Pick the consumer that matches the question:
findfor one item,anyfor yes or no,positionfor an index,countfor a number. Keepfilterfor when the answer genuinely is a set of items.
- Reach for
take_whileonly when the sequence is actually ordered by the thing being tested, and make that assumption visible in a name or a comment. It is a claim about the data, not about the filter.
- Use
retainwhen you own the collection and want it shorter. One pass, no allocation, and no second variable to keep in step.
- Use
partitionrather than two filters with opposite predicates, so that "opposite" is guaranteed by construction instead of by proofreading.
- Collect
Vec<&T>rather than cloning when the source will outlive the result. Reach for clones deliberately, not by default.
- Give a long chain an intermediate name once it passes three adapters.
let live = ...;thenlet busy = live.iter()...;reads better than nine lines of dots, and costs nothing if the intermediate is itself lazy.
Practice Exercises
- Select the readings over 100 from a
Vec<i32>three ways: withiter()and a two-layer dereference, withiter().copied()first, and withinto_iter(). Write down which predicate bodies compile with which chain, and what the compiler says when you get it wrong.
- Start from a
filterplusmapplusunwrapthat parses strings to numbers, and rewrite it as onefilter_map. Then, in the original version only, change the predicate to something slightly looser and show that the program now panics -- and explain why the rewritten version cannot.
- Take a deliberately jumbled list of numbers and produce both the
take_whileanswer and thefilteranswer for the same predicate. Write one sentence per result stating the question that result is the correct answer to.
- Rewrite the worked example's
partitionso that it splits intoVec<&Entry>instead of cloning. Get it compiling, then explain what now prevents the two halves from being returned out of a function that ownsentries.