Topic
Closures
A closure is an anonymous function that can capture variables from its surrounding code. Learn how to write them, store them, and pass them to other functions.
Quick Reference
ConceptWhat it means
ClosureAn anonymous function you can store in a variable and call later. Written with |params| body.
CaptureA closure can use variables from the surrounding code without being passed them as arguments.
Type inferenceYou do not need to annotate parameter or return types on closures. The compiler figures them out.
moveForces the closure to take ownership of captured variables instead of borrowing them.
Borrow in closureBy default, closures capture by the least restrictive method: immutable borrow if possible, then mutable, then move.
Stored closureA closure assigned to a variable so it can be called multiple times: let double = |x| x * 2;
TermWhat it meansWhen you use it
ClosureAn anonymous function written inline and stored in a variable. Uses |params| body syntax.When you need a short, one-off function to pass to map, filter, or store for later use.
CaptureA closure reads or modifies variables from the scope where it was defined, without receiving them as parameters.Every time a closure uses a variable that was not passed in as an argument.
Type inferenceThe compiler figures out parameter and return types from how the closure is first called.Always. You rarely need to annotate types on a closure explicitly.
moveForces the closure to take ownership of every variable it captures.When the closure needs to outlive the scope where the captured variable was created.
Mutable captureA closure that modifies a captured variable. Requires mut on both the variable and the closure binding.When you want a closure to update a counter or accumulate a value across multiple calls.
Type lockOnce a closure is called with a specific type, the compiler locks in that type for all future calls.After the first call locks the type, every subsequent call must pass the same type.