Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

Closures and capture in Rust

Reference for Rust closures: how they capture variables by reference, mutable reference or move, the Fn, FnMut and FnOnce traits, disjoint captures and returning closures.

A closure is an anonymous function that can use variables from the scope where it is written: |x| x + offset. The compiler turns each closure into a unique, unnamed struct that stores the captured variables, and implements one or more of the traits Fn, FnMut and FnOnce for it. Calling the closure calls a method on that struct.

How a variable is captured is chosen from how the closure body uses it: by shared reference if it only reads, by mutable reference if it modifies, by value if it consumes. The move keyword forces by-value capture of everything, which is what you need when the closure must outlive its scope, for example when returned or sent to another thread.

Rust
let offset = 10;
let add = |x: i32| x + offset;   // captures `offset` by shared reference
println!("{}", add(5));

Try it

Rust 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 move, disjoint fields 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.

Rust A closure that outlives its borrow

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.

The three traits

Trait The closure may Callable
FnOnce move captured values out of itself at least once; some closures only once
FnMut change captured values many times, needs &mut access
Fn only read captured values many times, even concurrently

Every closure implements FnOnce. If it never moves a captured value out, it also implements FnMut; if it additionally never mutates, it implements Fn. The traits form a chain: Fn is a subtrait of FnMut, which is a subtrait of FnOnce. A parameter bound of F: FnOnce() accepts everything, so use the weakest bound that your function needs; F: Fn() is the most restrictive for callers.

The closure's traits depend on the body, not on move. A move closure that only reads its captured String is still Fn; move just decides that the string is stored by value.

Usage notes

  • Capture precision: since edition 2021 the closure captures disjoint paths (config.hits) rather than whole variables, as the second example shows. In edition 2018 the same code fails because it borrows all of config. Captured values also drop at different times. See Editions.
  • Every closure has its own type. Two closures with identical bodies still have different types, so a Vec of closures needs Box<dyn Fn()> (or function pointers if nothing is captured).
  • Non-capturing closures coerce to plain function pointers (fn(i32) -> i32).
  • Closure types are Copy if all captures are Copy, and Clone if all captures are Clone. See move versus copy.
  • Threads: thread::spawn needs F: Send + 'static, so use move (or scoped threads, which allow borrowing).
  • Type inference fixes a closure's parameter types from its first use; calling it with another type afterwards is an error.
  • Recursion: closures cannot call themselves directly. Use a nested fn or pass the closure to itself.
  • Size: a closure is only as large as its captured data; a non-capturing closure is zero-sized.
  • Returning closures: impl Fn(...) for one concrete closure, Box<dyn Fn(...)> when branches differ.