Sub topic 2
How closures capture their environment
This chapter assumes you know ownership and borrowing, and that you can write a basic closure such as |x| x + 1. Here you will learn how Rust decides what a closure takes from the surrounding code, and why that decision affects what you can do with the variable afterward.
Capture follows use
A closure can read variables defined outside its body. Rust does not ask you to list them. The compiler looks at how the closure body uses each variable and picks the least demanding capture mode that works.
| Use inside the closure | Capture mode | Effect on the original variable |
|---|---|---|
| Only reads the value | Shared borrow (`&T`) | Still readable outside |
| Modifies the value | Mutable borrow (`&mut T`) | Not usable while the closure is alive |
| Moves the value out, for example by passing it to a function that takes ownership | By value (`T`) | Unusable afterward unless it is `Copy` |
Shared borrow
This closure only reads factor, so it holds a shared reference.
fn main() {
let factor = 3;
let scale = |x: i32| x * factor;
println!("{}", scale(4)); // 12
println!("{}", factor); // still readable: only borrowed
}A plain fn item cannot do this. Functions have no access to the local variables of the function that defines them.
Mutable borrow
When the body changes a captured variable, the closure holds a mutable reference. The closure binding itself must be declared mut, because calling it changes its internal state.
fn main() {
let mut count = 0;
let mut inc = || count += 1;
inc();
inc();
println!("{}", count); // 2
}The mutable borrow lasts until the closure's last use. The println! comes after the last call to inc, so the borrow checker accepts it. If you printed count between the two calls to inc, the program would not compile. The compiler would report that count cannot be borrowed as immutable because it is also borrowed as mutable.
Capture by value
If the body needs ownership, the closure takes the value.
fn main() {
let name = String::from("Ada");
let consume = || drop(name);
consume();
// `name` was moved into the closure; using it here would not compile.
}drop takes its argument by value, so the closure must own name. After the closure is created, name is no longer available in main. Because the closure gives up its captured String when it runs, you can call it only once.
Common errors
- Using a variable while a mutable closure is alive. Finish calling the closure first, or restructure so the closure's last call comes before the other use.
- Using a variable after a closure moved it. Clone the value before creating the closure, or pass the data into the closure as a parameter.
- Forgetting
muton the closure binding. If the body mutates captured state, the compiler asks forlet mut.
Capture mode is inferred from the body, not from how you call the closure. The next chapter shows how to override the inference with move.
Exercise
In the code below, which capture mode does the closure use for total, and does the final println! compile?
let mut total = 10;
let mut add = |n: i32| total += n;
add(5);
println!("{}", total);
Show answer
The closure mutates total, so it captures it by mutable borrow. The println! compiles because add is not used after that point, so the mutable borrow has ended. It prints 15.