Rust Tutorial: Closures
Anonymous functions that capture their environment. Fn, FnMut, FnOnce traits.
Closures
A closure is an anonymous function that can capture variables from its surrounding scope.
Closures are used extensively with iterators, threading, and callbacks.
What you'll learn in this Rust closures tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Basic closure — A closure is written as `|params| body`.
- Capturing by reference — Closures capture variables from their environment.
- Capturing by value with move — `move` forces the closure to take ownership of captured variables.
- Closures as arguments — Pass closures to functions that take `impl Fn`, `impl FnMut`, or `impl FnOnce`.
- Returning closures — Return a closure with `impl Fn` (when the type can be inferred) or `Box<dyn Fn>`.
- FnOnce — consume captured data — `FnOnce` closures can only be called once because they consume their captured data.
- Closures and iterators — Closures shine with iterator methods like map, filter, and fold.
- Mutable closure with FnMut — `FnMut` closures can mutate captured variables. They can be called multiple times.
Rust Closures concepts covered
- Closures