Sub topic 2
How closures capture their environment
This chapter assumes you know Rust ownership and borrowing, shared and mutable references, and the basic closure syntax |x| x + 1. The next chapters cover the move keyword and the Fn, FnMut and FnOnce traits. Here the question is narrower: when a closure uses a variable from the surrounding scope, what does it do to that variable?
The core rule
A closure that mentions a local variable captures it. The compiler picks the least demanding capture mode that the closure body allows:
- Shared borrow (
&T), if the body only reads the variable. - Mutable borrow (
&mut T), if the body modifies the variable. - Move (take ownership,
T), if the body consumes the variable, for example by passing it todropor returning it.
You never write the mode. The compiler infers it from how the body uses each variable, and the borrow checker then applies the usual rules to the resulting borrow.
| What the body does with the variable | Capture mode | Example body |
|---|---|---|
| Reads it, such as printing or calling `&self` methods | Shared borrow | `println!("{name}")` |
| Assigns to it or calls `&mut self` methods | Mutable borrow | `count += 1`, `v.push(4)` |
| Moves a non-`Copy` value out | Move | `drop(list)` |
Shared borrow
Reading a variable is the cheapest case. The closure holds a & reference, so the original stays usable, and any number of shared borrows can coexist.
fn main() {
let name = String::from("Ferris");
let greet = || println!("Hello, {name}");
greet();
println!("{name} is still usable");
greet();
}name is never moved, so the println! between the two calls compiles. Both the closure and the macro hold shared references.
Mutable borrow
When the body modifies a variable, the closure holds a &mut reference. Two rules follow. The closure binding must be declared mut, because calling it mutates its captured state. And while the closure is alive, nothing else may touch the variable.
fn main() {
let mut count = 0;
let mut inc = || count += 1;
inc();
inc();
// println!("{count}"); // error[E0502] if uncommented here:
// // inc is still used below? No, this is its last use above.
println!("{count}"); // 2
}The final println! compiles because the closure's last call is above it. Rust's borrow checker ends a borrow after its last use, not at the end of the scope. If you called inc() again after the println!, the closure's mutable borrow would still be live at the print, and the compiler would reject it with error[E0502]: cannot borrow count as immutable because it is also borrowed as mutable.
Capture by value
If the body moves a non-Copy value out of the variable, the closure must own it. Ownership transfers into the closure when the closure is created, not when it is called.
fn main() {
let list = vec![1, 2, 3];
let consume = || drop(list);
// println!("{:?}", list); // error[E0382]: borrow of moved value: `list`
consume();
}The commented-out line fails even though consume has not been called yet. The closure already owns list. Calling consume a second time would also fail, because the first call used up the vector. That limit is what makes this closure FnOnce, which a later chapter covers.
Copy types are captured by reference by default
Variables whose type is Copy, such as integers and bool, are not copied into a closure unless you ask. Reading one captures a reference to it, and the original stays live.
use std::mem::size_of_val;
fn main() {
let a: u8 = 1;
let b: u8 = 2;
let none = || 0;
let by_ref = || a + b;
let by_move = move || a + b;
// On a 64-bit platform this prints: 0 16 2
println!("{} {} {}", size_of_val(&none), size_of_val(&by_ref), size_of_val(&by_move));
}A closure is an unnamed struct whose fields are its captures. none captures nothing, so its size is zero. by_ref holds two 8-byte references. by_move holds two u8 values. The move keyword is covered in the next chapter. It appears here only to make the difference in what is stored visible.
Disjoint field capture (edition 2021)
Since the 2021 edition, a closure captures only the fields it names, not the whole struct. Other fields stay free to use.
struct Point {
x: i32,
y: i32,
}
fn main() {
let mut p = Point { x: 1, y: 2 };
let mut bump_x = || p.x += 10;
println!("{}", p.y); // allowed: the closure borrows only p.x
bump_x();
println!("{} {}", p.x, p.y); // 11 2
}In edition 2018 the closure would borrow all of p mutably, and reading p.y while bump_x is live would fail. The 2021 behavior applies to paths such as p.x. It does not reach through method calls, so p.get_x() still borrows the whole p.
Mixing capture modes
A single closure can capture different variables in different modes. Each variable gets the mode its own use requires.
fn main() {
let prefix = String::from("log");
let mut lines: Vec<String> = Vec::new();
let mut record = |msg: &str| lines.push(format!("{prefix}: {msg}"));
record("start");
record("stop");
println!("{:?}", lines); // ["log: start", "log: stop"]
}Here prefix is borrowed shared and lines is borrowed mutably. The closure is declared mut because at least one capture is mutable.
Why capture mode matters beyond the borrow checker
Capture mode determines how long a closure may live. A closure holding references cannot outlive the variables it borrows. Two situations expose this:
- Returning a closure. A closure that borrows a local variable cannot be returned from the function that owns the variable. The compiler reports
error[E0373]: closure may outlive the current function, but it borrows ...and suggestsmove. - Spawning a thread.
std::thread::spawnrequires the closure to be'static, so it cannot hold borrows of the spawning thread's stack. The same E0373 error appears, and the fix is againmove.
In both cases the fix is to change the capture from borrow to ownership. The next chapter covers how.
Common mistakes
- Forgetting
muton the closure binding.let inc = || count += 1;fails withcannot borrow inc as mutable. Declarelet mut inc. - Using the variable while a mutable-capturing closure is still live. Move the use before the closure is created, or after its last call.
- Expecting a closure to copy a value. A closure that only reads an integer still holds a reference to it. Later changes to that integer are visible through the closure, if the borrow rules permit them at all.
- Assuming a move happens at the call. For by-value captures, ownership moves when the closure expression is evaluated.
Exercise
Given let mut v = vec![1, 2, 3]; let mut add = || v.push(4);, which capture mode does the closure use? Does println!("{:?}", v); compile if it is placed between two calls to add()? What if it is placed after the last call?
Show answer
The body calls push, which takes &mut self, so v is captured by mutable borrow, and add must be declared mut. A println! between two calls fails with E0502, because the mutable borrow is still live until the second call. A println! after the last call compiles, because the borrow ends after the closure's last use.
Exercise
Why does let s = String::from("hi"); let f = || drop(s); println!("{s}"); fail even though f is never called? Which capture mode does f use?
Show answer
The body of f moves s out by passing it to drop, so s is captured by value. Ownership moves into the closure when it is created, so s is already moved when println! runs, giving error E0382 (borrow of moved value).