Rust Reference ยท Operators and Expressions
Closure expressions
Reference for Rust closure expressions: |params| body syntax, type inference, capture by reference, by mutable reference or by move, and Fn, FnMut and FnOnce.
A closure is an anonymous function written |params| body that can use variables from the place where it was created. Each closure expression has its own unique, unnameable type; the compiler generates a struct holding the captured variables and implements one or more of the traits Fn, FnMut and FnOnce for it. Parameter and return types are normally inferred from the first use.
How a closure captures each variable depends on what the body does with it: it borrows by shared reference if it only reads, by mutable reference if it modifies, and by value if it moves the variable out. The move keyword forces capture by value for everything, which is required when a closure must outlive its creator (threads, returned closures).
let add = |a, b| a + b; let greet = |name: &str| -> String { format!("hi {name}") }; let owner = move || data.len();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
|a, b| expr |a: T, b: U| -> R { block } move |a| expr || expr // no parameters |&(x, y)| x + y // patterns allowed async |x| expr // async closure (Rust 1.85)
| Trait | Closure may | Callable |
|---|---|---|
FnOnce |
move captured values out | at least once; all closures implement it |
FnMut |
mutate captured values | many times; needs mut binding |
Fn |
only read captured values | many times, even by shared reference |
Returns: a value of an anonymous closure type. If the body is not a block, the return type must not be written (|x| -> i32 x is a syntax error); with -> the body needs braces.
Usage notes
- Inference locks in: the first call fixes the parameter types.
let id = |x| x; id(1); id("a");fails becausexbecamei32. Use a generic function when you need several types. - Choosing the bound: accept
FnOnceif you call it once,FnMutif several times with mutation,Fnif it must be callable concurrently or by reference. The weaker the bound, the more closures are accepted. movedoes not meanFnOnce. It changes how values are captured (by value), not what the closure does with them. Amoveclosure that only reads is stillFn.- Copy/Clone: a closure is
CopyorClonewhen all its captures are. Closures that capture a&mutare neither. - Disjoint capture: since edition 2021 a closure captures only the fields it uses, so the example borrowing
p.xmutably andp.yimmutably compiles. In edition 2018 it would capture all ofp. - Function pointers:
fn(i32) -> i32accepts closures that capture nothing. A capturing closure needs generics,impl FnorBox<dyn Fn>. - Returning closures: use
impl Fn...for one concrete type,Box<dyn Fn...>when different closures may be returned. - Recursion is not possible directly because the closure cannot name itself; use a function or pass the closure to itself.
- Size: a closure's size is the sum of its captures, and calls are usually inlined, so iterator chains with closures compile to tight loops.
Related
- move
- Bitwise operators (
|as closure delimiter) - & and &mut
- Tutorial: Closures, Iterators, Threads