Skip to content
Theory · Closures and iterators · lesson 3 of 7

Capture modes and move

In the previous lesson a closure packed variables from its surroundings into a backpack. Now let's see exactly how it packs them.

Here the backpack picture stops being accurate. A real backpack carries the thing itself. A closure does not carry the thing away by default: it packs a note saying "it lies right here", that is, it borrows the variable. The variable itself stays with its owner in main.

Notes come in different kinds. With one you may only look at the thing, with another you may change it. And sometimes a closure does take the whole thing. The compiler, not the programmer, decides which way to use.

Three ways to capture

The compiler looks at what the closure's body does with a variable and takes the weakest way that is enough for the body. There are three ways, as for a function's parameters: &T, &mut T and T.

Reading

The body only reads the variable, so the closure takes a shared reference &, that is, a plain read-only reference. You can still read the variable from outside: there may be any number of readers.

Changing

The body changes the variable, so the closure takes a mutable reference &mut. While the closure will still be called, you cannot even read the variable itself: a mutable borrow is holding it.

Rust
fn main() {
    let name = String::from("Ann");
    let greet = || println!("hi, {name}");
    greet(); // hi, Ann
    println!("{}", name.len()); // 3

    let mut count = 0;
    let mut inc = || count += 1;
    inc();
    inc();
    println!("{count}"); // 2
}

Let's walk through the example line by line:

  1. greet only reads name, so it captures it by shared reference.
  2. name.len() works after the call: name still belongs to its owner.
  3. inc changes count, so it captures it by mutable reference.
  4. inc is declared with let mut: the closure holds &mut count, and each call changes the closure itself.
  5. After the last call of inc the borrow ends, and println! reads count. It prints 2.

If you put println!("{count}") between the two calls of inc, the compiler refuses with error E0502: you cannot read count while a mutable reference holds it.

Handing over ownership

The body gives the value away, for example returns it, so the closure takes the whole variable.

Rust
fn main() {
    let name = String::from("Ann");
    let give = || name;
    let s = give();
    println!("{s}"); // Ann
}

give returns name, and you can only return what you own. So the closure moves name into itself, and the call hands it over to s. There is nothing left to give a second time: calling give() again is error E0382.

The move keyword

move in front of a closure makes it take every captured variable by value, even when the body only reads it. This is the backpack packed with the originals instead of notes.

  • A String moves into the closure, and you can no longer use it outside (E0382).
  • A Copy value such as an i32 is copied: the closure has its own copy, and the original variable stays as it was.
Rust
fn main() {
    let mut count = 0;
    let mut inc = move || {
        count += 1;
        println!("{count}");
    };
    inc(); // 1
    inc(); // 2
    println!("{count}"); // 0
}

The closure changes its own copy of count, so it prints 1 and 2. The variable count in main stays zero. You need move when a closure must live longer than the variables it captured, for example when you hand it to another thread.

The Fn, FnMut and FnOnce traits

Every closure implements call traits. Which ones depends on what the body does with what it captured:

  • Fn: the body only reads; you may call it any number of times;
  • FnMut: the body changes what it captured; you may call it many times, but the variable holding the closure is declared with let mut;
  • FnOnce: the body gives a captured value away; you may call it only once.

greet is Fn, inc is FnMut, give is FnOnce. move does not affect the trait: move || println!("{name}") takes name but only reads it, so it stays Fn. A function that accepts a closure states in its signature which of the traits it needs.

"What closure traits are there and how do they differ?" is a frequent interview question. Answer by the body: does it read, change or give away.

Common mistake

The variable was declared with mut, but the closure that changes it was not:

Rust
fn main() {
    let mut count = 0;
    let inc = || count += 1; // ✗
    inc();
    println!("{count}");
}
TEXT
error[E0596]: cannot borrow `inc` as mutable, as it is not declared as mutable

The program does not compile, and nothing is printed. inc holds a mutable reference to count, so a call changes the closure itself. mut on count allows changing the variable, and mut on inc allows calling a closure that changes it. You need both: let mut inc = || count += 1;.

Key points

  • A closure captures a variable the weakest way that is enough for its body: reading takes &, changing takes &mut, giving away takes the value.
  • A closure that changes a captured variable is declared with let mut, or you get error E0596.
  • move takes what is captured by value; a Copy value is copied, and the closure changes its own copy.
  • Reading means Fn, changing means FnMut, giving a captured value away means FnOnce.