Closure (Rust)
A closure is an anonymous function that can capture variables from the surrounding scope. Written with |params| body, closures are Rust's lightweight inline functions, used heavily with iterators.
Rust
Closures look like |x| x + 1 and can capture variables from where they are defined — by reference, by mutable reference, or by value. Rust infers how to capture based on what the body does; add the move keyword to force capture by value, which is required when the closure outlives its scope or moves to another thread.
The compiler categorizes closures by the traits Fn (captures by shared ref), FnMut (by mutable ref), and FnOnce (consumes captures). Function parameters that accept closures are typed with these bounds, e.g. F: Fn(i32) -> i32.
Closures are everywhere in idiomatic Rust: .map(), .filter(), .for_each(), sorting with a custom comparator, and callbacks. Each closure has its own anonymous type, so to store or return one you use impl Fn... or box it as Box<dyn Fn...>.
Syntax
let add = |a, b| a + b;
let make = move || captured;Examples
Rust
fn main() {
let factor = 3;
let times = |x: i32| x * factor; // captures factor
println!("{}", times(5));
}Output:
15