Closures
A closure is an anonymous function that can capture bindings from its scope. You write |x| x + 1 and pass it to iterators, threads, and APIs that need a callback.
Detailed Explanation
let add = |a, b| a + b; creates a closure. The compiler infers parameter and return types from how you use it. You may write them: |a: i32, b: i32| -> i32 { a + b }. A block body needs a return type only when inference cannot see it. The closure is a value. Each closure expression has its own unique anonymous type, even if two closures have the same signature.
Capture is the difference from an fn item. |x| x + offset borrows offset if it only reads it, mutably borrows if it assigns, and moves it if you write move |x| x + offset or if the closure outlives the current stack frame (as when you send it to a thread). move forces every capture by move. Without move, Rust picks the weakest capture that still compiles.
Closures implement one or more of the Fn, FnMut, and FnOnce traits depending on how they capture. A closure that only reads its captures is Fn. One that mutates them is FnMut. One that consumes them is FnOnce. Function items and non-capturing closures implement all three. APIs pick the weakest they need: Iterator::map wants FnMut, thread::spawn wants FnOnce + Send.
You cannot write the closure's type by name. You store it as a generic F: Fn(i32) -> i32, as impl Fn(i32) -> i32, or as Box<dyn Fn(i32) -> i32> when the closure must be a uniform type. The boxed form is a trait object and heap-allocates the captures.
Why closures exist: iterators would be unusable if every map needed a named function that cannot see local state. Threads would need a struct of captured fields and an impl FnOnce. The closure is that struct, written inline.
When you write a closure: a short callback, especially on an iterator. When the body is long or reused, write a function or a method. When you need to name the type in a struct, use F: Fn... or a boxed dyn Fn.
Code Examples
fn main() {
let offset = 10;
let add = |x| x + offset; // borrows offset
println!("{}", add(5)); // prints: 15
let mut total = 0;
let mut acc = |x| total += x; // mutably borrows total
acc(1);
acc(2);
println!("{total}"); // prints: 3
let name = String::from("ada");
let greet = move || println!("hi {name}"); // takes name
greet(); // prints: hi ada
}Common Gotchas
A capturing closure is not an `fn` pointer
`fn(i32) -> i32` only accepts function items and non-capturing closures. Use `impl Fn` or `Box<dyn Fn>` when you capture.
`move` moves every capture
A `move` closure used with `thread::spawn` will take the whole `Vec` even if you only needed one element. Clone first, or capture a reference if the thread does not outlive it.
Each closure expression has a distinct type
You cannot put two different closures in a `Vec` without boxing them as `dyn Fn`.
Inference of closure types is picky
Sometimes you must annotate the first parameter or the return type. The error is `type annotations needed`, not a runtime miss.