Let’s Learn Rust 009: Closures and Iterators
These two features are everywhere in Rust. Once you learn them you will see them in almost every codebase, every library, and every piece of idiomatic Rust you read. I avoided them longer than I should have early on because the syntax looked intimidating. That was a mistake. They are actually one of the most satisfying parts of the language to use.
1. What Is a Closure?
A closure is a function you define inline, right where you need it, that can capture variables from its surrounding scope.
In Python you have lambdas. In Java you have lambda expressions introduced in Java 8. In C++ you have lambda functions. Rust closures are similar but more powerful because of how they interact with ownership.
The basic syntax:
fn main() {
let add = |x, y| x + y;
println!("{}", add(3, 4)); // 7
}
fn main() {
let add = |x, y| x + y;
println!("{}", add(3, 4)); // 7
}
The pipes |x, y| hold the parameters. No need to declare types, Rust infers them. The body x + y is the return value.
For multi-line closures you add braces:
0 {
String::from("positive")
} else {
String::from("non-positive")
}
};
println!("{}", describe(5));
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let describe = |n: i32| {
if n > 0 {
String::from("positive")
} else {
String::from("non-positive")
}
};
println!("{}", describe(5));
}
fn main() {
let describe = |n: i32| {
if n > 0 {
String::from("positive")
} else {
String::from("non-positive")
}
};
println!("{}", describe(5));
}
2. Closures Capture Their Environment
This is what separates closures from regular functions. A closure can reach out and grab variables from the scope it was defined in.
threshold; // captures `threshold`
println!("{}", is_big(15)); // true
println!("{}", is_big(5)); // false
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let threshold = 10;
let is_big = |n| n > threshold; // captures `threshold`
println!("{}", is_big(15)); // true
println!("{}", is_big(5)); // false
}
fn main() {
let threshold = 10;
let is_big = |n| n > threshold; // captures `threshold`
println!("{}", is_big(15)); // true
println!("{}", is_big(5)); // false
}
In Python, a lambda does the same thing. In C++, you have to explicitly list what to capture with [threshold] or [&threshold]. Rust figures it out automatically based on how you use the captured variable.
3. The Three Closure Traits
When I first ran into compile errors related to closures I had no idea what Fn, FnMut, and FnOnce meant. Here is the simple breakdown:
FnOncecan be called once. It takes ownership of the captured variables. Once called, those variables are gone.FnMutcan be called multiple times and can mutate what it captures.Fncan be called multiple times and only borrows what it captures immutably.
Every closure automatically implements one or more of these depending on what it does.
<button data-code="fn apply_once String>(f: F) {
println!("{}", f()); // can only call f once
}
fn apply_twice i32>(f: F) {
println!("{}", f());
println!("{}", f()); // can call f multiple times
}
fn main() {
let msg = String::from("hello");
apply_once(move || msg); // msg is moved into closure, consumed on call
let x = 5;
apply_twice(|| x * 2); // x is borrowed, can be used many times
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn apply_once<F: FnOnce() -> String>(f: F) {
println!("{}", f()); // can only call f once
}
fn apply_twice<F: Fn() -> i32>(f: F) {
println!("{}", f());
println!("{}", f()); // can call f multiple times
}
fn main() {
let msg = String::from("hello");
apply_once(move || msg); // msg is moved into closure, consumed on call
let x = 5;
apply_twice(|| x * 2); // x is borrowed, can be used many times
}
fn apply_once<F: FnOnce() -> String>(f: F) {
println!("{}", f()); // can only call f once
}
fn apply_twice<F: Fn() -> i32>(f: F) {
println!("{}", f());
println!("{}", f()); // can call f multiple times
}
fn main() {
let msg = String::from("hello");
apply_once(move || msg); // msg is moved into closure, consumed on call
let x = 5;
apply_twice(|| x * 2); // x is borrowed, can be used many times
}
You rarely need to think about which trait to use explicitly. The compiler tells you when there is a mismatch.
4. move Closures
Sometimes you want the closure to own its captured variables rather than borrow them. You saw this in the threads article. The move keyword forces it:
fn main() {
let name = String::from("Zeeshan");
let greet = move || println!("Hello, {}!", name);
greet();
// println!("{}", name); // ERROR: name was moved into the closure
}
fn main() {
let name = String::from("Zeeshan");
let greet = move || println!("Hello, {}!", name);
greet();
// println!("{}", name); // ERROR: name was moved into the closure
}
This comes up constantly when passing closures to threads or storing them for later use.
5. Iterators
An iterator is something that produces a sequence of values one at a time. Any type that implements the Iterator trait can be used in loops, chained with adapters, and collected into data structures.
The core of the trait is one method:
Option;
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
Every time you call next(), you get Some(value) or None when the sequence is done. The for loop in Rust is just syntax sugar for calling next() repeatedly.
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for n in numbers.iter() {
println!("{}", n);
}
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for n in numbers.iter() {
println!("{}", n);
}
}
6. Iterator Adapters
This is where things get interesting. Iterators come with a set of methods called adapters that transform the sequence. They are lazy, meaning they do nothing until you actually consume the iterator.
In Python this is similar to generator expressions. In Java these are streams. The Rust versions are generally faster because there is no boxing or virtual dispatch.
map transforms each element:
<button data-code="fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let doubled: Vec = numbers.iter().map(|&n| n * 2).collect();
println!("{:?}", doubled); // [2, 4, 6, 8, 10]
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let doubled: Vec<i32> = numbers.iter().map(|&n| n * 2).collect();
println!("{:?}", doubled); // [2, 4, 6, 8, 10]
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let doubled: Vec<i32> = numbers.iter().map(|&n| n * 2).collect();
println!("{:?}", doubled); // [2, 4, 6, 8, 10]
}
filter keeps elements that match a condition:
<button data-code="fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let evens: Vec = numbers.iter().filter(|&&n| n % 2 == 0).collect();
println!("{:?}", evens); // [2, 4, 6]
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let evens: Vec<&i32> = numbers.iter().filter(|&&n| n % 2 == 0).collect();
println!("{:?}", evens); // [2, 4, 6]
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let evens: Vec<&i32> = numbers.iter().filter(|&&n| n % 2 == 0).collect();
println!("{:?}", evens); // [2, 4, 6]
}
fold reduces a sequence to a single value (similar to Python’s reduce or JavaScript’s reduce):
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let sum = numbers.iter().fold(0, |acc, &n| acc + n);
println!("{}", sum); // 15
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let sum = numbers.iter().fold(0, |acc, &n| acc + n);
println!("{}", sum); // 15
}
For common reductions, Rust has shortcuts like .sum() and .product().
7. Chaining Adapters
This is where Rust iterators feel really clean. You can chain multiple adapters together and the whole chain runs in one pass:
<button data-code="fn main() {
let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result: Vec = data
.iter()
.filter(|&&n| n % 2 == 0) // keep evens: 2,4,6,8,10
.map(|&n| n * n) // square them: 4,16,36,64,100
.collect();
println!("{:?}", result);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result: Vec<i32> = data
.iter()
.filter(|&&n| n % 2 == 0) // keep evens: 2,4,6,8,10
.map(|&n| n * n) // square them: 4,16,36,64,100
.collect();
println!("{:?}", result);
}
fn main() {
let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result: Vec<i32> = data
.iter()
.filter(|&&n| n % 2 == 0) // keep evens: 2,4,6,8,10
.map(|&n| n * n) // square them: 4,16,36,64,100
.collect();
println!("{:?}", result);
}
In Python this would be a list comprehension. In Java you would use stream().filter().map().collect(). The Rust version is similar to Java streams but with zero overhead at runtime because the compiler optimizes the whole chain into a single loop.
8. Useful Iterator Methods
enumerate gives you the index alongside each value:
fn main() {
let fruits = vec!["apple", "banana", "cherry"];
for (i, fruit) in fruits.iter().enumerate() {
println!("{}: {}", i, fruit);
}
}
fn main() {
let fruits = vec!["apple", "banana", "cherry"];
for (i, fruit) in fruits.iter().enumerate() {
println!("{}: {}", i, fruit);
}
}
zip combines two iterators into pairs:
<button data-code="fn main() {
let names = vec!["Alice", "Bob", "Carol"];
let scores = vec![95, 87, 92];
let combined: Vec = names.iter().zip(scores.iter()).collect();
for (name, score) in &combined {
println!("{} scored {}", name, score);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let names = vec!["Alice", "Bob", "Carol"];
let scores = vec![95, 87, 92];
let combined: Vec<_> = names.iter().zip(scores.iter()).collect();
for (name, score) in &combined {
println!("{} scored {}", name, score);
}
}
fn main() {
let names = vec!["Alice", "Bob", "Carol"];
let scores = vec![95, 87, 92];
let combined: Vec<_> = names.iter().zip(scores.iter()).collect();
for (name, score) in &combined {
println!("{} scored {}", name, score);
}
}
flat_map maps and then flattens one level:
<button data-code="fn main() {
let sentences = vec!["hello world", "foo bar baz"];
let words: Vec = sentences
.iter()
.flat_map(|s| s.split_whitespace())
.collect();
println!("{:?}", words); // ["hello", "world", "foo", "bar", "baz"]
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let sentences = vec!["hello world", "foo bar baz"];
let words: Vec<&str> = sentences
.iter()
.flat_map(|s| s.split_whitespace())
.collect();
println!("{:?}", words); // ["hello", "world", "foo", "bar", "baz"]
}
fn main() {
let sentences = vec!["hello world", "foo bar baz"];
let words: Vec<&str> = sentences
.iter()
.flat_map(|s| s.split_whitespace())
.collect();
println!("{:?}", words); // ["hello", "world", "foo", "bar", "baz"]
}
any and all check conditions:
5)); // true
println!("{}", numbers.iter().all(|&n| n % 2 != 0)); // true (all odd)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let numbers = vec![1, 3, 5, 7, 9];
println!("{}", numbers.iter().any(|&n| n > 5)); // true
println!("{}", numbers.iter().all(|&n| n % 2 != 0)); // true (all odd)
}
fn main() {
let numbers = vec![1, 3, 5, 7, 9];
println!("{}", numbers.iter().any(|&n| n > 5)); // true
println!("{}", numbers.iter().all(|&n| n % 2 != 0)); // true (all odd)
}
9. Implementing Iterator Yourself
You can make any type iterable by implementing the trait. This is something C++ developers will recognize from custom iterator classes, but the Rust version is cleaner:
Self {
Counter { count: 0, max }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option {
if self.count < self.max {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
fn main() {
let counter = Counter::new(5);
let sum: u32 = counter.sum();
println!("{}", sum); // 15
// or use it with all the other adapters
let doubled: Vec = Counter::new(5).map(|n| n * 2).collect();
println!("{:?}", doubled); // [2, 4, 6, 8, 10]
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
struct Counter {
count: u32,
max: u32,
}
impl Counter {
fn new(max: u32) -> Self {
Counter { count: 0, max }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.count < self.max {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
fn main() {
let counter = Counter::new(5);
let sum: u32 = counter.sum();
println!("{}", sum); // 15
// or use it with all the other adapters
let doubled: Vec<u32> = Counter::new(5).map(|n| n * 2).collect();
println!("{:?}", doubled); // [2, 4, 6, 8, 10]
}
struct Counter {
count: u32,
max: u32,
}
impl Counter {
fn new(max: u32) -> Self {
Counter { count: 0, max }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.count < self.max {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
fn main() {
let counter = Counter::new(5);
let sum: u32 = counter.sum();
println!("{}", sum); // 15
// or use it with all the other adapters
let doubled: Vec<u32> = Counter::new(5).map(|n| n * 2).collect();
println!("{:?}", doubled); // [2, 4, 6, 8, 10]
}
Once you implement Iterator, you get all the adapters for free. That is the power of the trait system working alongside iterators.
10. Closures and Iterators Together
The real payoff is combining both. Most iterator adapters take closures as arguments, which is why these two topics belong together:
<button data-code="fn main() {
let employees = vec![
("Alice", 85000),
("Bob", 72000),
("Carol", 91000),
("David", 68000),
];
let senior_names: Vec = employees
.iter()
.filter(|(_, salary)| *salary > 80000)
.map(|(name, _)| *name)
.collect();
println!("{:?}", senior_names); // ["Alice", "Carol"]
let total_payroll: i32 = employees.iter().map(|(_, s)| s).sum();
println!("Total payroll: {}", total_payroll);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn main() {
let employees = vec![
("Alice", 85000),
("Bob", 72000),
("Carol", 91000),
("David", 68000),
];
let senior_names: Vec<&str> = employees
.iter()
.filter(|(_, salary)| *salary > 80000)
.map(|(name, _)| *name)
.collect();
println!("{:?}", senior_names); // ["Alice", "Carol"]
let total_payroll: i32 = employees.iter().map(|(_, s)| s).sum();
println!("Total payroll: {}", total_payroll);
}
fn main() {
let employees = vec![
("Alice", 85000),
("Bob", 72000),
("Carol", 91000),
("David", 68000),
];
let senior_names: Vec<&str> = employees
.iter()
.filter(|(_, salary)| *salary > 80000)
.map(|(name, _)| *name)
.collect();
println!("{:?}", senior_names); // ["Alice", "Carol"]
let total_payroll: i32 = employees.iter().map(|(_, s)| s).sum();
println!("Total payroll: {}", total_payroll);
}
This kind of code would be a multi-step loop in Java pre-streams, a list comprehension in Python, or verbose and error-prone in C with raw arrays. In Rust it reads almost like English and compiles to efficient machine code.
Summary
Closures are inline functions that capture their environment. The three closure traits (FnOnce, FnMut, Fn) describe how a closure interacts with what it captures. Iterators produce sequences lazily and come with a rich set of adapters. Combine them and you get expressive, fast, and safe data transformation pipelines.
Once these click you will stop writing manual for loops for almost everything. I use them in pretty much every function I write now.
What’s Next
Next we go into Smart Pointers. Box, Rc, RefCell and the patterns they enable. Understanding these will also fill in some gaps about why Arc and Mutex work the way they do.
Happy coding and safe assembling!
Follow this series and join us in mastering Rust from scratch!


