Module lessons (1/3)
Closure, Capture &T / &mut T / move and Trait Fn*
Closure syntax, immutable/mutable/move capture inference and difference between trait Fn, FnMut and FnOnce.
What you'll learn in this lesson
- Declare anonymous functions (closure) with automatic inference of parameter types and return.
- Understand how Rust captures variables from the environment:
&T,&mut T, or by property (move). - Distinguish the three closure traits (
FnOnce,FnMut,Fn) and the related bounds in the API.
Overview
A closure in Rust is an anonymous function capable of capturing variables from the enclosing scope. Unlike many languages that allocate all closures on the Heap with garbage-collected pointers, rustc compiles each closure as a dedicated anonymous struct on the Stack!
While fn require explicit annotations on each parameter and return, closures infer types from first use:
Sections covered in this lesson
- 11. Compact syntax and type inference
- 22. The three automatic capture modes
- 33. Hierarchy of traits
Fn,FnMutandFnOnce - 44.
moveforced and generic parameters - 5Practical exercises
- 6Check for understanding
Unlock "Closure, Capture &T / &mut T / move and Trait Fn*" and the full Course Rust curriculum
Closure syntax, immutable/mutable/move capture inference and difference between trait `Fn`, `FnMut` and `FnOnce`.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Rust plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.