Rust Abstractions · 18 min · free with an account

Closures

Lesson preview · about 30%

A closure is a function that also carries the environment it captured.

Core idea

The body decides the trait: read is Fn, mutate is FnMut, consume is FnOnce.

Start with the idea

Rust infers whether a closure needs a shared borrow (Fn), a mutable borrow (FnMut), or ownership (FnOnce) from what the body does. move forces capture by value, which is what makes a closure safe to send to another thread — the ownership question is answered at compile time rather than by a convention.

A closure is a callable value that may carry data from the surrounding scope. The first example only reads total, so it can satisfy Fn; the second changes count, so it needs mutable access and satisfies FnMut. A closure that consumes a captured value may be callable only once and satisfy FnOnce. These traits describe what callers may do with the closure, not just what the closure returns.

Capture is inferred per variable.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery