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. Called with ().
  • Capture: Automatically capture variables by reference (Fn), mutable reference (FnMut), or move (FnOnce), based on usage. move keyword forces ownership transfer. Standard borrow rules apply.
  • Traits: Fn, FnMut, FnOnce traits define closure capabilities, used as bounds in functions.
  • 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.