Map and filter
Quick answer
Use iterator adapters to describe a sequence of transformations without writing a loop for each step. map transforms items and filter keeps items satisfying a condition.
Lazy pipelines
Adapters produce iterators rather than immediately allocating results. A consumer such as collect, count or a for loop drives the work. map receives the iterator item by value; filter receives a reference to the item, so for an iterator of references the predicate may see a reference to a reference.
fn main() { let doubled: Vec<_> = (1..=3).map(|n| n * 2).collect(); println!("{doubled:?}");}Expected stdout (not executed):
[2, 4, 6]Collect drives the map and creates a vector.
fn main() { let scores = [8, 12, 17]; let passing: Vec<_> = scores.into_iter().filter(|n| *n >= 10).collect(); println!("{passing:?}");}Expected stdout (not executed):
[12, 17]The filter predicate borrows each integer item.
Common mistake
Creating a lazy map alone does not execute its closure for each item.
Try it yourself
Filter numbers greater than zero, then square them and collect the results.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Map and filter — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A map closure increments a counter but the adapter is never consumed. What happens?
Map and filter — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let doubled: Vec<_> = (1..=3).map(|n| n * 2).collect(); println!("{doubled:?}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Map and filter — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let scores = [8, 12, 17]; let passing: Vec<_> = scores.into_iter().filter(|n| *n >= 10).collect(); println!("{passing:?}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.