Skip to content
ImagineWorld

Closures and Functional Patterns

node_idnode-book_oop-to-rust_chapter-07-closures-and-functional-patterns
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleClosures and Functional Patterns
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Closures and Functional Patterns

Section titled “Chapter 7 — Closures and Functional Patterns”

Forma dat esse rei. (Form gives being to a thing.)

Object-oriented programming centers on objects as the primary abstraction: data bundled with the methods that operate on it. Functional programming centers on functions: transformations that take inputs and produce outputs. Rust embraces both paradigms, and closures are where they meet. A closure is a function that captures variables from its surrounding environment, creating a callable value that carries its context with it. This capability enables patterns that are awkward or impossible with methods alone.

Closures appear throughout Rust code. Iterators use them for transformations and filtering. Threads use them to specify what code runs concurrently. APIs use them for callbacks and customization points. Understanding closures deeply is essential for writing idiomatic Rust, and that understanding requires grasping not just the syntax but the ownership and borrowing semantics that make Rust’s closures both powerful and safe.

Closure syntax and type inference

Rust closures use a concise syntax that differs from regular function definitions. Where functions use fn and require explicit type annotations, closures use vertical bars to delimit parameters and typically infer types from context.

The simplest closure takes no parameters and returns a value:

let greeting = || "hello";

Parameters appear between the vertical bars:

let add_one = |x| x + 1;
let sum = |a, b| a + b;

For closures with multiple statements, braces create a block:

let process = |value| {
let doubled = value * 2;
let adjusted = doubled + 10;
adjusted
};

Type inference makes most closures concise. The compiler infers parameter and return types from how the closure is used. When you pass a closure to a function expecting a specific signature, the compiler knows what types the closure must have. When you call a closure with specific argument types, the compiler infers from those.

However, once a closure’s types are inferred, they are fixed. A closure cannot be generic over its argument types the way a function can. If you call add_one(5), the closure is inferred to take i32. Calling add_one(5.0) afterward would fail because the type is already fixed.

When inference is insufficient or when clarity benefits from explicitness, you can annotate closure types:

let parse_int = |s: &str| -> i32 {
s.parse().unwrap_or(0)
};

The syntax mirrors function syntax: parameters with types, an arrow, and a return type. These annotations are rarely necessary in practice because context usually provides enough information.

Closures can be stored in variables, passed to functions, returned from functions, and stored in data structures. They are values like any other, though their types are unique and unnameable. Each closure has a distinct anonymous type generated by the compiler. Two closures with identical code have different types. This affects how closures are stored and passed, a topic explored in detail when discussing the Fn traits.

Capture modes

The distinctive feature of closures is their ability to capture variables from the enclosing scope. A regular function can only access its parameters and items defined within it. A closure can access variables from the scope where it is defined, carrying those values with it when it moves elsewhere.

How a closure captures variables determines what it can do with them and what the original scope can do after the closure is created. Rust’s ownership system extends to captures, ensuring that closures cannot create dangling references or data races. The compiler analyzes how each captured variable is used within the closure and chooses the most permissive capture mode that remains safe.

Capturing by reference

When a closure only reads a captured variable, the compiler captures it by shared reference. The closure borrows the variable immutably, allowing both the closure and the original scope to read the value.

let message = String::from("hello");
let print_message = || println!("{}", message);
print_message();
println!("Original: {}", message); // Still accessible

The closure print_message captures message by reference. Calling the closure borrows message for the duration of the call. Between calls, other code can access message. The closure does not take ownership; it shares access.

This capture mode enables closures that observe their environment without disturbing it. A closure passed to a sorting function might capture a configuration value by reference, reading it to influence the sort order without taking ownership or modifying it.

The borrow lasts as long as the closure exists, not just while it executes. If the closure is stored and lives beyond the current scope, the compiler ensures the referenced variables live at least as long. This is where lifetime analysis becomes relevant, as explored in Chapter 2.

Capturing by mutable reference

When a closure modifies a captured variable, the compiler captures it by mutable reference. This requires the closure itself to be mutable because calling it mutates state outside the closure’s body.

let mut counter = 0;
let mut increment = || {
counter += 1;
counter
};
println!("{}", increment()); // 1
println!("{}", increment()); // 2
println!("Final: {}", counter); // 2

The closure increment captures counter by mutable reference. Because calling the closure mutates counter, the closure variable itself must be declared mut. This requirement makes mutation visible at the call site: you can see that calling increment () might change something because increment is mutable.

While the closure holds a mutable reference, the original variable cannot be accessed through any other path. The borrow checker enforces exclusivity just as it does for any mutable reference. Attempting to read counter between closure calls would fail to compile if the closure still exists.

Mutable capture enables closures that accumulate state across calls. Counters, running totals, and state machines can all be implemented as closures that modify captured state.

Capturing by value with move

Sometimes a closure needs to own its captured variables rather than borrowing them. The move keyword forces all captures to be by value, transferring ownership into the closure.

let name = String::from("Alice");
let greet = move || println!("Hello, {}", name);
// name is no longer accessible here; it moved into the closure
greet();
greet(); // Can be called multiple times

After move, the closure owns name. The original variable is no longer accessible because ownership transferred to the closure. The closure can be called multiple times, stored in data structures, or sent to other threads, all because it owns its data rather than borrowing it.

The move keyword is essential when closures outlive the scope where they are created. Spawning a thread requires a closure that owns its data because the thread might outlive the spawning function.

Returning a closure from a function requires ownership because borrows cannot outlive the function.

fn make_greeter(name: String) -> impl Fn() {
move || println!("Hello, {}", name)
}

Without move, this function would fail to compile. The closure would try to borrow name, but name is a local variable that disappears when the function returns. With move, the closure takes ownership, and name lives as long as the closure does.

Even with move, the compiler still optimizes what kind of ownership is taken. A move closure that only reads a Copy type copies the value rather than moving it. A move closure that only reads a non-Copy type moves it. The move keyword affects whether capture is by reference or by value; it does not prevent the compiler from choosing the most appropriate value capture.

The Fn traits: Fn, FnMut, FnOnce

Closures implement traits from the standard library that describe how they can be called. These traits form a hierarchy: FnOnce is the base, FnMut refines it, and Fn refines further. Understanding this hierarchy is crucial for writing functions that accept closures and for understanding why certain closures work in some contexts but not others.

FnOnce represents closures that can be called at least once. Every closure implements FnOnce because every closure can be called at least once. Calling an FnOnce closure might consume it, making further calls impossible. The name reflects this: the closure can be called “once” (at minimum).

FnMut represents closures that can be called multiple times and might mutate their captured state. An FnMut closure can be called repeatedly, but calling it requires mutable access to the closure itself because the call might change captured variables.

Fn represents closures that can be called multiple times without mutating captured state. An Fn closure can be called through a shared reference because calling it does not modify anything. This is the most flexible trait: an Fn closure can be called from multiple places simultaneously (if accessible), and the calls are guaranteed not to interfere.

The hierarchy creates a subtyping relationship: every Fn closure is also FnMut (calling through a shared reference is a special case of calling through a mutable reference), and every FnMut closure is also FnOnce (being able to call multiple times implies being able to call once).

How the compiler chooses

The compiler analyzes each closure’s body to determine which traits it implements. A closure that only reads captured variables implements all three traits: Fn, FnMut, and FnOnce. A closure that mutates captured variables implements FnMut and FnOnce but not Fn. A closure that moves out of captured variables implements only FnOnce.

let s = String::from("hello");
// Implements Fn, FnMut, FnOnce (only reads capture)
let len = || s.len();
// Implements FnMut, FnOnce (mutates capture)
let mut count = 0;
let mut counter = || { count += 1; count };
// Implements only FnOnce (moves out of capture)
let consume = || drop(s);

The distinction matters when writing functions that accept closures. A function requiring Fn can be called repeatedly with the same closure. A function requiring FnMut needs mutable access to the closure. A function requiring FnOnce might consume the closure, preventing further use.

The iterator adapter map requires FnMut because it calls the closure for each element. The thread spawn function requires FnOnce plus Send because it calls the closure exactly once in another thread. A caching function might require Fn so it can call the closure from multiple cache misses without synchronization.

When accepting closures in your own functions, choose the most permissive bound that works. Requiring FnOnce accepts all closures. Requiring FnMut excludes closures that can only be called once. Requiring Fn excludes closures that mutate state. Start with the loosest bound and tighten only if the function’s behavior requires it.

The following example demonstrates the three trait levels with concrete code that shows when each can be called:

fn main() {
let data = vec![1, 2, 3, 4, 5];
// FnOnce: this closure can only be called once because it moves `data` out
let consume = || {
let owned = data; // Takes ownership of data
println!("Sum: {}", owned.iter().sum::<i32>());
owned // Returns owned data, consuming it from closure's environment
};
let result = consume(); // First call: works
// consume(); // Second call: ERROR - closure already consumed its capture
// FnMut: can be called multiple times, mutates captured state
let mut counter = 0;
let mut increment = || {
counter += 1;
counter
};
println!("{}", increment()); // 1
println!("{}", increment()); // 2
println!("{}", increment()); // 3
// Fn: can be called multiple times, no mutation of captures
let greeting = "Hello";
let greet = || println!("{}", greeting);
greet();
greet();
greet(); // Can call as many times as needed
// The hierarchy in action: Fn closures can be used where FnOnce is required
fn call_once<F: FnOnce()>(f: F) {
f();
}
call_once(greet); // Fn closure works where FnOnce is expected
}

Understanding which trait a closure implements helps predict compilation errors. A closure that moves values out of its captures cannot be called twice because the values are gone after the first call. The compiler prevents such errors by restricting which trait the closure implements.

Closures as trait objects

Because closures have unique anonymous types, you cannot directly name a closure’s type. This creates challenges when storing closures in collections or returning them from functions. Two approaches exist: trait objects and impl Trait.

Trait objects erase the closure’s concrete type, storing it behind a pointer:

let handlers: Vec<Box<dyn Fn(i32) -> i32>> = vec![
Box::new(|x| x + 1),
Box::new(|x| x * 2),
Box::new(|x| x - 3),
];
for handler in &handlers {
println!("{}", handler(10));
}

The Box<dyn Fn(i32) -> i32> type stores any closure matching the signature. The boxing allocates the closure on the heap and stores a pointer. The dyn keyword indicates dynamic dispatch: calls go through a vtable rather than being inlined.

Trait objects have runtime cost (heap allocation, indirect calls) but enable heterogeneous collections and runtime polymorphism. When you need a collection of closures with different capture environments, trait objects are the tool.

The alternative is impl Trait for return types:

fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}

This returns an opaque type that implements Fn. The compiler knows the concrete type and can inline calls, but the type is hidden from callers. This works for returning a single closure from a function but not for heterogeneous collections.

Higher-order functions

A higher-order function is a function that takes functions as arguments or returns functions as results. Closures enable higher-order programming by making it easy to pass behavior as values. This style is fundamental to working with iterators and pervades Rust’s standard library.

Consider filtering a collection. In object-oriented style, you might define a filter interface and pass an implementation. In functional style with closures, you pass the predicate directly:

let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evens: Vec<_> = numbers.iter()
.filter(|&&x| x % 2 == 0)
.collect();
let squares: Vec<_> = numbers.iter()
.map(|&x| x * x)
.collect();

The filter and map methods are higher-order functions. They take closures specifying what to filter or how to transform. The closures are lightweight, defined inline where they are used, making the code concise and readable.

Writing higher-order functions in Rust uses generic bounds on the Fn traits:

fn apply_twice<F>(f: F, x: i32) -> i32
where
F: Fn(i32) -> i32,
{
f(f(x))
}
let result = apply_twice(|x| x + 1, 5); // 7

The function is generic over F, which must implement Fn(i32) -> i32. Any closure or function pointer matching this signature works. The compiler monomorphizes the function for each distinct closure type, enabling inlining and optimization.

Higher-order functions enable composition. Instead of writing a complex transformation as a single function, break it into simple pieces and compose them:

fn compose<F, G>(f: F, g: G) -> impl Fn(i32) -> i32
where
F: Fn(i32) -> i32,
G: Fn(i32) -> i32,
{
move |x| g(f(x))
}
let add_one = |x| x + 1;
let double = |x| x * 2;
let add_one_then_double = compose(add_one, double);
println!("{}", add_one_then_double(5)); // 12

This style treats transformations as data, combining them to build complex behavior from simple parts.

Closures vs function pointers

Rust distinguishes between closures and function pointers. A function pointer is a pointer to a function item defined with fn. It has a known size (the size of a pointer) and contains no captured state. A closure might have captured state, giving it an unknown size at compile time unless you know the specific closure type.

Function pointer types use the fn keyword:

fn add_one(x: i32) -> i32 {
x + 1
}
let f: fn(i32) -> i32 = add_one;
println!("{}", f(5));

Function pointers implement all three Fn traits, so they can be passed any function expecting a closure. However, closures that capture state cannot be coerced to function pointers because they need to store state somewhere.

The practical implication is that APIs accepting function pointers are less flexible than APIs accepting generic Fn bounds. A function pointer parameter cannot accept closures that capture variables. A generic Fn parameter accepts both function pointers and closures.

When writing APIs, prefer generic bounds over function pointers unless you specifically need the properties of function pointers (known size, no captures, FFI compatibility). Generic bounds are more flexible and enable more use cases. Function pointers are appropriate when interacting with C code through FFI or when you need to store functions in a collection without heap allocation and know they will not capture state.

Closures that capture nothing can sometimes be coerced to function pointers, but this conversion is not always automatic. When you need a function pointer specifically, using an actual function definition is clearer than relying on closure coercion.

Common patterns

Closures enable patterns that appear throughout Rust codebases. Recognizing these patterns helps you write idiomatic code and understand libraries that use them.

Callbacks and event handlers

Callbacks are functions invoked in response to events. Closures are natural callbacks because they can capture context needed to handle the event. A GUI framework might accept closures for button clicks. A network library might accept closures for connection events.

struct Button {
on_click: Box<dyn FnMut()>,
}
impl Button {
fn new(handler: impl FnMut() + 'static) -> Self {
Button {
on_click: Box::new(handler),
}
}
fn click(&mut self) {
(self.on_click)();
}
}

The button stores a boxed closure that will be called when clicked. The FnMut bound allows the handler to modify captured state (like updating a counter). The ‘static bound requires the closure to own its captures rather than borrowing from the creating scope, ensuring the closure lives as long as the button.

Callbacks can capture whatever context they need. A handler might capture a reference to an application state struct, a channel sender for communicating events, or configuration values influencing the response. The closure packages all this context into a single callable value.

Lazy initialization

Lazy initialization defers expensive computation until the result is actually needed. Closures capture the computation itself, executing it only when required.

The standard library’s Option::get_or_insert_with and Result::unwrap_or_else methods accept closures for lazy values:

let mut cached: Option<ExpensiveResult> = None;
let value = cached.get_or_insert_with(|| {
println!("Computing...");
compute_expensive_result()
});

The closure is only called if cached is None. Subsequent accesses return the cached value without recomputing. This pattern avoids wasted computation when the value might not be needed.

For more complex lazy initialization, the once_cell crate (with types now in std as of Rust 1.70) provides Lazy, which holds a closure and initializes on first access:

use std::sync::LazyLock;
static CONFIG: LazyLock<Config> = LazyLock::new(|| {
load_config_from_file()
});

The closure runs exactly once, on first access to CONFIG. Subsequent accesses return the computed value. This is useful for expensive global initialization that should happen lazily.

Custom iterators with closures

Iterator adaptors accept closures to customize their behavior. Beyond the standard map, filter, and fold, you can create custom iteration patterns by combining closures with iterator methods.

The scan method carries state through an iteration, updated by a closure:

let running_sum: Vec<i32> = vec![1, 2, 3, 4, 5]
.into_iter()
.scan(0, |state, x| {
*state += x;
Some(*state)
})
.collect();
// [1, 3, 6, 10, 15]

The closure receives mutable state and each element, returning an Option that controls when iteration stops.

The take_while method uses a closure to control termination:

let prefix: Vec<_> = vec![1, 2, 3, 10, 4, 5]
.into_iter()
.take_while(|&x| x < 10)
.collect();
// [1, 2, 3]

For fully custom iteration logic, implement Iterator manually, but closures often suffice for one-off iteration patterns without the boilerplate of a custom iterator type.

Closures and iterators combine to create a declarative style where you describe transformations rather than writing explicit loops. The compiler optimizes these chains aggressively, often producing code as efficient as hand-written loops while being more readable and composable.

Essential Points

Closures are anonymous functions that capture variables from their environment. They use a concise syntax with vertical bar parameter delimiters and typically rely on type inference. Each closure has a unique anonymous type, requiring generics or trait objects when storing or passing closures.

Capture modes determine how closures access their environment. By default, closures capture variables by reference when only reading, by mutable reference when modifying, and by value when needed for the closure to be independent of its creation scope. The move keyword forces capture by value, essential when closures outlive their creating scope.

The Fn trait hierarchy describes how closures can be called. FnOnce closures can be called at least once. FnMut closures can be called multiple times but require mutable access. Fn closures can be called through shared references. The compiler automatically implements the appropriate traits based on how closures use their captures.

Higher-order functions take closures as arguments or return them as results. This style enables iterator adaptors, customizable APIs, and functional composition. When writing functions that accept closures, use generic bounds for flexibility and performance.

Function pointers are distinct from closures. They point to function items without captured state. Function pointers work where closures are expected but are less flexible because they cannot capture environment variables.

Common closure patterns include callbacks for event handling, lazy initialization to defer computation, and iterator customization for declarative data transformation. These patterns appear throughout the Rust ecosystem and form the foundation of idiomatic Rust style.

The next chapter addresses error handling, where closures play a supporting role in methods like unwrap_or_else and map_err that transform or provide defaults for error cases.