Closures in Rust
Table of Contents
Anonymous functions that can capture values from the enclosing
scope. Closures are the primary way to pass behaviour as a value
in Rust — to iterators, threads, callbacks, and sorting
functions. The compiler infers capture mode automatically,
choosing the least restrictive Fn trait that satisfies the
closure's needs.
Related: Rust Ownership in Rust Iterators Functional Programming
Syntax
// Basic closure
let add_one = |x| x + 1;
add_one(5) // 6
// With explicit types
let add_two = |x: i32| -> i32 { x + 2 };
// Multi-line
let greet = |name: &str| {
let msg = format!("Hello, {name}!");
println!("{msg}");
};
// Capturing from environment
let factor = 3;
let multiply = |x| x * factor; // borrows factor immutably
multiply(10) // 30
Capture Modes — The Three Fn Traits
The compiler chooses the capture mode based on what the closure does with captured variables. Ordering from least to most restrictive:
Fn — immutable borrow
Captures by &T. Can be called any number of times. The captured
variable remains usable outside the closure.
let greeting = String::from("Hello");
let print = |name: &str| println!("{greeting}, {name}!");
print("Alice");
print("Bob");
println!("{greeting}"); // still valid — only borrowed
FnMut — mutable borrow
Captures by &mut T. Can be called multiple times but mutates
captured state. The closure must be declared mut.
let mut count = 0;
let mut increment = || {
count += 1;
count
};
increment(); // 1
increment(); // 2
// println!("{count}"); // error — mutably borrowed by closure
FnOnce — move (ownership transfer)
Captures by value — takes ownership of the captured variable. Can only be called once because the variable is consumed.
let data = vec![1, 2, 3];
let consume = || {
println!("{data:?}");
drop(data); // drops data — ownership consumed
};
consume();
// consume(); // error — FnOnce already consumed data
// println!("{data:?}"); // error — data was moved
The move Keyword
Forces the closure to take ownership of all captured variables, even if it could get by with a reference. Required when passing closures to threads:
let message = String::from("hello from thread");
let handle = std::thread::spawn(move || {
// message is moved into the closure — thread owns it
println!("{message}");
});
handle.join().unwrap();
// println!("{message}"); // error — message was moved
Without move, the compiler would complain that message might
not live long enough for the thread.
Common Uses
Iterator adaptors
let numbers = vec![1, 2, 3, 4, 5];
let doubled: Vec<i32> = numbers.iter()
.map(|x| x * 2)
.collect();
let evens: Vec<&i32> = numbers.iter()
.filter(|&&x| x % 2 == 0)
.collect();
let sum: i32 = numbers.iter()
.filter(|&&x| x > 2)
.map(|x| x * x)
.sum();
Custom sorting
let mut words = vec!["banana", "apple", "cherry"]; words.sort_by(|a, b| a.len().cmp(&b.len())); // sort by length
Returning closures
Closures have unique anonymous types — return them via impl Fn:
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n // n is moved into the returned closure
}
let add5 = make_adder(5);
add5(10) // 15
Fn Trait Bounds in Function Signatures
// Accept any callable that takes i32 and returns i32
fn apply(f: impl Fn(i32) -> i32, x: i32) -> i32 {
f(x)
}
// Store a closure in a struct (requires Box for dynamic dispatch)
struct Callback {
func: Box<dyn Fn(i32) -> i32>,
}
Tips
- The compiler infers the
Fntrait — you rarely need to specify it explicitly; addmovewhen crossing thread boundaries or when the closure outlives its defining scope - If a closure needs to mutate state, declare it
mut:let mut f = || { ... }; impl Fnin a return type is the idiomatic way to return a closure without allocating; useBox<dyn Fn>when the concrete type is unknown at compile time- Iterator chains with closures are zero-cost — they compile to the same machine code as hand-written loops