Rust Iterators and Closures: map, filter, and move Semantics
Iterators are lazy and monomorphised into loops. The three consumption forms, the Fn trait ladder, and why an adapter chain with no consumer does nothing.

Quick Summary
Iterators in Rust are lazy and zero-cost. An adapter such as map, filter, or take builds a value that describes work; nothing runs until a consumer such as collect, sum, for_each, count, or a for loop drives it. The compiler monomorphises the whole chain into a single loop, so v.iter().filter(|x| **x > 2).map(|x| x * 2).sum::<i32>() compiles to roughly the same machine code as a hand-written loop — the chain is structure, not overhead.
Consumption comes in three forms, and mixing them up is the most common borrow error in Rust. iter() yields &T, iter_mut() yields &mut T, and into_iter() yields T, consuming the collection. A for loop calls into_iter() on the thing you give it, which is why for x in &v borrows and for x in v moves.
Closures implement one of Fn, FnMut, or FnOnce, chosen by how they capture: by reference, by mutable reference, or by value (with move). The trait is part of the closure's type, so a function that needs to call a closure repeatedly must accept Fn or FnMut, while one that consumes a captured value can accept FnOnce.
Basic syntax and query signatures
let v = vec![1, 2, 3, 4, 5];
// Lazy adapters
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
let evens: Vec<&i32> = v.iter().filter(|x| **x % 2 == 0).collect();
let first_two: Vec<_> = v.iter().take(2).copied().collect();
let total: i32 = v.iter().sum();
let max: Option<&i32> = v.iter().max();
// Consumers
let n = v.iter().count();
let any_big = v.iter().any(|x| *x > 4);
let all_pos = v.iter().all(|x| *x > 0);
let found: Option<&i32> = v.iter().find(|x| **x == 3);
// Chaining adapters that change shape
let pairs: Vec<(usize, i32)> = v.iter().copied().enumerate().filter(|(i, _)| i % 2 == 0).collect();
let flat: Vec<i32> = vec![vec![1, 2], vec![3]].into_iter().flatten().collect();
let zipped: Vec<(i32, &str)> = v.iter().copied().zip(["a", "b"]).collect();
let chained: Vec<i32> = v.iter().copied().chain([9, 10]).collect();
// Folding and accumulating
let sum = v.iter().fold(0, |acc, x| acc + x);
let running: Vec<i32> = v.iter().scan(0, |acc, x| { *acc += x; Some(*acc) }).collect();
let product = v.iter().copied().reduce(|a, b| a * b);Closures and the three capture modes:
let mut count = 0;
let mut bump = || { count += 1; }; // FnMut: captures by mutable reference
bump();
println!("{count}"); // 1
let name = String::from("db");
let say = move || println!("{name}"); // FnOnce-ish: owns name, still callable
say();
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 { f(x) }
fn apply_once<F: FnOnce() -> String>(f: F) -> String { f() }// Returning an iterator: impl Trait keeps it allocation-free
fn evens(v: &[i32]) -> impl Iterator<Item = &i32> + '_ {
v.iter().filter(|x| **x % 2 == 0)
}
// Custom iterator: implement next()
struct Counter { n: u32, max: u32 }
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.n < self.max { self.n += 1; Some(self.n) } else { None }
}
}Key comparison table
| Iteration form | Yields | Collection after | Typical use |
|---|---|---|---|
v.iter() | &T | Borrowed | Read-only pass |
v.iter_mut() | &mut T | Mutably borrowed | In-place updates |
v.into_iter() | T | Moved (consumed) | Transform and drop |
&v in a for | &T | Borrowed | Same as iter() |
v in a for | T | Moved | Last use of the collection |
| Closure trait | Captures | Callable | Example bound |
|---|---|---|---|
Fn | &T | Any number of times | F: Fn(i32) -> i32 |
FnMut | &mut T | Repeated, mutating | F: FnMut(i32) |
FnOnce | T by value | Exactly once | F: FnOnce() -> T |
move || | Forces by-value capture | Depends on body | thread::spawn(move || ...) |
| Adapter | Lazy | Effect |
|---|---|---|
map | Yes | One-to-one transform |
filter | Yes | Keeps matching items |
filter_map | Yes | Transform plus optional drop |
flat_map | Yes | One-to-many, flattened |
take / skip | Yes | Bound the stream |
take_while / skip_while | Yes | Bound by predicate |
peekable | Yes | Look ahead one item |
collect / sum / count | No | Consumes |
fold / reduce | No | Consumes into one value |
for_each | No | Consumes with side effects |
Practical edge cases and deep dives
1. Nothing happens until something consumes
let v = vec![1, 2, 3];
v.iter().map(|x| println!("{x}")); // warning: unused `Map` that must be used; prints nothing
v.iter().for_each(|x| println!("{x}")); // prints three linesThe compiler warns because adapters return #[must_use] values. In a chain you meant to execute, the consumer at the end is not optional — and map is not a loop.
2. Borrowing the collection while a closure captures it
let v = vec![1, 2, 3];
// v.iter().for_each(|x| v.push(*x)); // E0502: cannot borrow v as mutable
// Collect first, then extend
let extra: Vec<i32> = v.iter().map(|x| x * 2).collect();
v.extend(extra);The closure holds an immutable borrow of v for the whole chain, so any mutation inside it conflicts. The same shape appears with retain in other languages' idioms: the fix is to compute the values, then apply them.
3. impl Iterator with a lifetime
fn long_words(text: &str) -> impl Iterator<Item = &str> + '_ {
text.split_whitespace().filter(|w| w.len() > 4)
}Without + '_, the compiler cannot tie the returned iterator's lifetime to text, and you get E0700 hidden type captures lifetime. The underscore says "borrowed from an elided input", which is exactly the relationship you mean.
4. Two different branches cannot return two different iterator types
// error[E0308]: if and else have different types (Filter<...> vs Map<...>)
// fn f(v: &[i32], evens_only: bool) -> impl Iterator<Item = &i32> {
// if evens_only { v.iter().filter(|x| **x % 2 == 0) } else { v.iter().map(|x| x) }
// }
// Box the dispatch, or unify with Option/chain
fn f(v: &[i32], evens_only: bool) -> Box<dyn Iterator<Item = &i32> + '_> {
if evens_only {
Box::new(v.iter().filter(|x| **x % 2 == 0))
} else {
Box::new(v.iter())
}
}impl Trait in return position names exactly one hidden type, so branches must produce the same one. Boxing trades an allocation for dynamic dispatch when the branches genuinely differ.
5. collect needs a target type
// error[E0282]: type annotations needed
// let v = (0..3).map(|x| x * 2).collect();
let v: Vec<i32> = (0..3).map(|x| x * 2).collect();
let s: String = ['a', 'b'].iter().collect();
let set: std::collections::HashSet<i32> = (0..3).collect();collect is generic over every FromIterator type, so the target has to be known. This is a feature: the same chain produces a Vec, a String, a HashMap, or a Result without changing the adapters.
// Fallible collection stops at the first Err
let nums: Result<Vec<i32>, _> = ["1", "2", "x"].iter().map(|s| s.parse::<i32>()).collect();
assert!(nums.is_err());6. Sliding windows and chunks without a crate
let v = [1, 2, 3, 4, 5];
let chunks: Vec<&[i32]> = v.chunks(2).collect(); // [1,2] [3,4] [5]
let windows: Vec<&[i32]> = v.windows(3).collect(); // [1,2,3] [2,3,4] ...
// Mean of each window
let means: Vec<f64> = v.windows(3)
.map(|w| w.iter().sum::<i32>() as f64 / w.len() as f64)
.collect();windows and chunks are slice methods, not iterator adapters, so they borrow the slice and carry its lifetime. chunks_mut mutates in place and is the standard way to process a large buffer in blocks.
7. Closures in structs need a type parameter or a box
// A named type: generic, monomorphised, no allocation
struct Handler<F: Fn(&str) -> String> { f: F }
// A stored heterogeneous closure: dynamic dispatch
struct AnyHandler { f: Box<dyn Fn(&str) -> String + Send + Sync> }
impl<F: Fn(&str) -> String> Handler<F> {
fn call(&self, s: &str) -> String { (self.f)(s) }
}Each closure literal has a unique anonymous type, so Handler<F> needs the parameter and Box<dyn Fn> needs the allocation. Collections of callbacks are the case where the box is the right default.
Common mistakes and runtime errors
| Error / symptom | Cause | Fix |
|---|---|---|
E0502 borrow conflict | Closure mutates while iterating | Collect first, then mutate |
E0282 type annotations needed | collect target unknown | Annotate Vec<_>/Result<...> |
E0308 in if/else returning impl Iterator | Two different hidden types | Box<dyn Iterator> or unify |
E0700 hidden type captures lifetime | Missing + '_ | Add the lifetime bound |
E0596 cannot borrow as mutable | FnMut closure declared without mut | let mut f = ... |
E0382 in a thread closure | Captured by reference | move plus cloned handles |
| Adapter chain does nothing | No consumer | Add collect/for_each/count |
E0277 closure not Send | Captures Rc/RefCell | Arc/Mutex instead |
E0716 temporary dropped | Iterator over a temporary | Bind the collection to a let |
sum() type ambiguous | No target type | sum::<i32>() |
for x in v then reuse v | into_iter() moved the collection | for x in &v |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.