BorrowCheck › Rust language core

Closures

Capture modes, Fn / FnMut / FnOnce, the move keyword, closures as parameters, function pointers.

The topic explains closures: how the compiler picks a capture mode for each captured variable from what the body does with it, and why since the 2021 edition a closure captures individual fields rather than the whole struct. The questions check which of the Fn, FnMut and FnOnce traits a closure implements, why the body decides this and the move keyword does not, and when a closure is itself Copy. The subtopic on move covers what exactly is transferred into the closure: ownership of a string, a copy of a value taken at creation, or the reference itself, and why a returned closure or one stored in a Box<dyn Fn> needs move. A separate part treats closures as parameters and return values: impl Fn in argument and return position, Box<dyn FnOnce>, calling a closure stored in a struct field, and a for<'a> bound for a borrowed argument. The last subtopic is about function pointers: how a function item type differs from fn, why it is zero-sized, and why a capturing closure does not coerce to fn.

39 questions: 17 basic, 18 intermediate, 4 advanced. 5 info pages, 23 sources.

Subtopics

  1. Capture modes
  2. Fn, FnMut, FnOnce
  3. The move keyword
  4. Closures as parameters and return values
  5. Function pointers

Previous: Collections and iterators · Next: Type conversions