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
| Concept | What it means |
|---|---|
| Closure | An anonymous function you can store in a variable and call later. Written with |params| body. |
| Capture | A closure can use variables from the surrounding code without being passed them as arguments. |
| Type inference | You do not need to annotate parameter or return types on closures. The compiler figures them out. |
| move | Forces the closure to take ownership of captured variables instead of borrowing them. |
| Borrow in closure | By default, closures capture by the least restrictive method: immutable borrow if possible, then mutable, then move. |
| Stored closure | A closure assigned to a variable so it can be called multiple times: let double = |x| x * 2; |
| Term | What it means | When you use it |
|---|---|---|
| Closure | An 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. |
| Capture | A 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 inference | The 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. |
| move | Forces 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 capture | A 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 lock | Once 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. |