Python Closures & Functional Iterators (map, filter, collect)
Closures are anonymous functions that can capture variables from their enclosing environment (|param| expr). Combined with Rust’s lazy Iterator trait adaptors (.map, .filter, .fold, .collect), they produce zero-cost functional data transformation pipelines.
"Iterator adaptors are like interlocking industrial conveyor sections: .filter() drops defective parts, .map() polishes them, and .collect() packs them into a finished crate—and the whole conveyor only spins when the final crate is demanded (lazy evaluation)."
Deep Dive: How It Works
Closures: Anonymous functions defined with vertical bars: |x, y| x + y.
Lazy Iterators: Iterator adaptors do no work until a consuming method like .collect(), .sum(), or .count() is called.
.collect(): Assembles transformed iterator streams back into collections like Vec<T>.
Syntax Blueprint
let doubled: Vec<i32> = numbers.iter().filter(|&&x| x > 5).map(|x| x * 2).collect();
Chains functional transformation stages into a single optimized SIMD loop.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting type annotation on .collect().Why it happens: collect() can build Vec, HashSet, String, etc. The compiler needs to know target collection type.
How to fix: Use let res: Vec<i32> = ... or .collect::<Vec<_>>() (the turbofish operator).
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Filter and double numbers with iterator
Given let numbers = vec![1, 2, 3, 4, 5];
Use .into_iter().filter(|x| x % 2 == 0).map(|x| x * 10).collect::<Vec<i32>>()
Print "Even doubled: [20, 40]".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.