Module 14 Exercises — Closures & Iterators
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be able to explain:
- what
movedoes and when you need it; - why a chain with no
collect()prints nothing; - the difference between
iter(),iter_mut()andinto_iter().
For every loop you write in these drills, try rewriting it as an iterator chain — and then decide honestly which reads better. Sometimes the loop wins, and knowing when is part of the skill.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 14.1 — Closure capture modes
For each closure, name the trait it implements (Fn, FnMut, or FnOnce):
let v = vec![1, 2, 3];
let a = || println!("{v:?}");
let mut count = 0;
let b = || count += 1;
let s = String::from("x");
let c = || drop(s);
let d = |x: i32| x + 1;Answers
a: Fn. b: FnMut. c: FnOnce. d: Fn (captures nothing).
🟢 Exercise 14.2 — Rewrite loops as iterator chains
// A
let mut evens = Vec::new();
for x in &nums { if x % 2 == 0 { evens.push(x * x); } }
// B
let mut total = 0;
for (i, x) in nums.iter().enumerate() { if i % 2 == 0 { total += x; } }
// C
let mut found = None;
for x in &nums { if *x > 100 { found = Some(x); break; } }Solution
let evens: Vec<i32> = nums.iter().filter(|x| *x % 2 == 0).map(|x| x * x).collect();
let total: i32 = nums.iter().step_by(2).sum();
let found = nums.iter().find(|x| **x > 100);Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 14.3 — Implement Counter and combine it
Implement an iterator counting 1..=5, then compute: zip it with a skipped copy of itself, multiply pairs, keep multiples of 3, and sum.
Solution
struct Counter { count: u32 }
impl Counter { fn new() -> Self { Counter { count: 0 } } }
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.count < 5 { self.count += 1; Some(self.count) } else { None }
}
}
fn main() {
let sum: u32 = Counter::new()
.zip(Counter::new().skip(1)) // (1,2) (2,3) (3,4) (4,5)
.map(|(a, b)| a * b) // 2 6 12 20
.filter(|x| x % 3 == 0) // 6 12
.sum();
assert_eq!(sum, 18);
}🟡 Exercise 14.4 — Text statistics pipeline
Given a paragraph, produce with a single iterator chain each of:
- the number of unique words (case-insensitive)
- the longest word
- the average word length
- a
HashMap<char, usize>of first-letter counts
Solution
use std::collections::{HashMap, HashSet};
fn main() {
let text = "the quick brown fox jumps over the lazy dog The END";
let words: Vec<String> = text
.split_whitespace()
.map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase())
.filter(|w| !w.is_empty())
.collect();
let unique: HashSet<&String> = words.iter().collect();
println!("unique: {}", unique.len());
println!("longest: {:?}", words.iter().max_by_key(|w| w.len()));
let avg = words.iter().map(|w| w.len()).sum::<usize>() as f64 / words.len() as f64;
println!("avg length: {avg:.2}");
let firsts: HashMap<char, usize> = words.iter()
.filter_map(|w| w.chars().next())
.fold(HashMap::new(), |mut m, c| { *m.entry(c).or_insert(0) += 1; m });
println!("{firsts:?}");
}fold with a HashMap accumulator is the functional alternative to a for loop with
entry — both are idiomatic; pick whichever reads better.
🟡 Exercise 14.5 — Custom Fn parameter
Write fn transform_all<T, F>(items: Vec<T>, f: F) -> Vec<T> where F: Fn(T) -> T and a
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C.
Solution
fn transform_all<T, F: Fn(T) -> T>(items: Vec<T>, f: F) -> Vec<T> {
items.into_iter().map(f).collect()
}
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
move |x| g(f(x))
}
fn main() {
println!("{:?}", transform_all(vec![1, 2, 3], |x| x * 10));
let add_then_show = compose(|x: i32| x + 1, |x: i32| format!("<{x}>"));
println!("{}", add_then_show(41)); // <42>
}Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 14.6 — Lazy prime iterator
Implement struct Primes { found: Vec<u64>, next: u64 } as an Iterator<Item = u64> using
trial division against already-found primes. Then:
- print the first 20 primes
- find the first prime above 10_000
- sum all primes below 1_000 Verify laziness: the iterator must not compute anything until consumed.
Solution
struct Primes { found: Vec<u64>, next: u64 }
impl Primes {
fn new() -> Self { Primes { found: Vec::new(), next: 2 } }
}
impl Iterator for Primes {
type Item = u64;
fn next(&mut self) -> Option<u64> {
loop {
let candidate = self.next;
self.next += 1;
let is_prime = self.found
.iter()
.take_while(|p| *p * *p <= candidate)
.all(|p| candidate % p != 0);
if is_prime {
self.found.push(candidate);
return Some(candidate);
}
}
}
}
fn main() {
let first20: Vec<u64> = Primes::new().take(20).collect();
println!("{first20:?}");
let big = Primes::new().find(|p| *p > 10_000).unwrap();
println!("first prime > 10000: {big}"); // 10007
let sum: u64 = Primes::new().take_while(|p| *p < 1_000).sum();
println!("sum below 1000: {sum}"); // 76127
let lazy = Primes::new().map(|p| { println!("computed {p}"); p });
println!("no output above this line");
let _: Vec<u64> = lazy.take(3).collect();
}Note take_while(|p| p*p <= candidate) — the found vector is sorted, so trial division
stops at the square root automatically.
Self-check
- Which closure trait does a closure that mutates a captured variable implement?
- Why does
make_adderneedmove? - What does "iterators are lazy" mean concretely?
- What's the difference between
iter(),iter_mut(), andinto_iter()? - What does
collect::<Result<Vec<_>, _>>()do?
Answers
FnMut.- The captured
nis a local; withoutmovethe returned closure would hold a reference to a dead stack frame. - Adaptors build a struct chain and do no work until a consuming method calls
next. - They yield
&T,&mut T, andTrespectively; the last consumes the collection. - Turns an iterator of
Results into aResultcontaining a collection, returning the firstErrif any.
