12.6 Summary
Closures (or lambda expressions) in Rust are anonymous functions that capture variables from their environment. They enable concise, expressive code for passing behavior.
- Syntax:
|params| -> ReturnType { body }, types often inferred. Braces optional for single expressions. Closures assigned to variables or passed as arguments are called using the standard()syntax. - Capture: Automatically capture variables by shared reference (
Fn), exclusive reference (FnMut), or by taking ownership (FnOnce), based on usage.movekeyword forces ownership transfer. Standard borrow rules apply. - Traits:
Fn,FnMut,FnOncetraits define closure capabilities, used as bounds in functions. They represent shared access, exclusive access, and consumption, respectively. - First-Class: Can be stored, passed, and returned like any value.
- Comparison: Safer, more ergonomic alternative to C’s function pointer +
void*context. - Performance: Usually stack-allocated. Zero-cost abstraction via generics (
impl Fn...). Dynamic dispatch (dyn Fn...) incurs overhead.
Closures are fundamental to idiomatic Rust, powering iterators, concurrency, and customizable logic while upholding Rust’s safety and performance goals.