Skip to content
Tutorials Center
My learning

Topics

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).

Rust
let add = |a, b| a + b;
let greet = |name: &str| -> String { format!("hi {name}") };
let owner = move || data.len();

Try it

Rust Syntax and the three capture modes

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.

Rust Passing and returning closures

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

Rust
|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 because x became i32. Use a generic function when you need several types.
  • Choosing the bound: accept FnOnce if you call it once, FnMut if several times with mutation, Fn if it must be callable concurrently or by reference. The weaker the bound, the more closures are accepted.
  • move does not mean FnOnce. It changes how values are captured (by value), not what the closure does with them. A move closure that only reads is still Fn.
  • Copy/Clone: a closure is Copy or Clone when all its captures are. Closures that capture a &mut are neither.
  • Disjoint capture: since edition 2021 a closure captures only the fields it uses, so the example borrowing p.x mutably and p.y immutably compiles. In edition 2018 it would capture all of p.
  • Function pointers: fn(i32) -> i32 accepts closures that capture nothing. A capturing closure needs generics, impl Fn or Box<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.