Skip to main content
Module 8 · Lesson 1 of 315/24 in the course~18 min
Module lessons (1/3)

Closure, Capture &T / &mut T / move and Trait Fn*

Lesson preview5 hands-on exercises readyCourse Rust · Module 8 — Closures and Iterators Zero-Cost

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

  1. 11. Compact syntax and type inference
  2. 22. The three automatic capture modes
  3. 33. Hierarchy of traits Fn, FnMut and FnOnce
  4. 44. move forced and generic parameters
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 8 — Closures and Iterators Zero-Cost

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.