Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~3 min readRust
#Rust#Functional Programming#Iterators
3D illustration of a zero-cost iterator chain of map, filter and fold stations reducing a stream to one value

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

rust
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:

rust
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() }
rust
// 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 formYieldsCollection afterTypical use
v.iter()&TBorrowedRead-only pass
v.iter_mut()&mut TMutably borrowedIn-place updates
v.into_iter()TMoved (consumed)Transform and drop
&v in a for&TBorrowedSame as iter()
v in a forTMovedLast use of the collection
Closure traitCapturesCallableExample bound
Fn&TAny number of timesF: Fn(i32) -> i32
FnMut&mut TRepeated, mutatingF: FnMut(i32)
FnOnceT by valueExactly onceF: FnOnce() -> T
move ||Forces by-value captureDepends on bodythread::spawn(move || ...)
AdapterLazyEffect
mapYesOne-to-one transform
filterYesKeeps matching items
filter_mapYesTransform plus optional drop
flat_mapYesOne-to-many, flattened
take / skipYesBound the stream
take_while / skip_whileYesBound by predicate
peekableYesLook ahead one item
collect / sum / countNoConsumes
fold / reduceNoConsumes into one value
for_eachNoConsumes with side effects

Practical edge cases and deep dives

1. Nothing happens until something consumes

rust
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 lines

The 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

rust
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

rust
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

rust
// 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

rust
// 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.

rust
// 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

rust
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

rust
// 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 / symptomCauseFix
E0502 borrow conflictClosure mutates while iteratingCollect first, then mutate
E0282 type annotations neededcollect target unknownAnnotate Vec<_>/Result<...>
E0308 in if/else returning impl IteratorTwo different hidden typesBox<dyn Iterator> or unify
E0700 hidden type captures lifetimeMissing + '_Add the lifetime bound
E0596 cannot borrow as mutableFnMut closure declared without mutlet mut f = ...
E0382 in a thread closureCaptured by referencemove plus cloned handles
Adapter chain does nothingNo consumerAdd collect/for_each/count
E0277 closure not SendCaptures Rc/RefCellArc/Mutex instead
E0716 temporary droppedIterator over a temporaryBind the collection to a let
sum() type ambiguousNo target typesum::<i32>()
for x in v then reuse vinto_iter() moved the collectionfor x in &v

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.