skip to content

In Rust, why does printing `clicks` between two calls of `let mut on_click = || clicks += 1;` fail with E0502, and what fixes it?

level: middleimportance: should knowfreq 58%

answer

  1. the borrow lives in the closure
  2. creation to last use
  3. binding needs let mut
  4. pass the counter in

basics

~20 s

The closure stores a &mut clicks from the moment it is created until its last call, so reading clicks in between conflicts with that exclusive borrow. Read after the last call, or have the closure take &mut i32 as a parameter.

solid answer

~40 s

A closure that assigns to a captured variable stores a mutable reference to it inside the closure value. That borrow starts when the closure is created and, under non-lexical lifetimes, lasts until the closure's last use, not just while each call runs. A `println!("{clicks}")` between two calls needs a shared borrow while the `&mut` is still alive, so rustc reports E0502, cannot borrow `clicks` as immutable because it is also borrowed as mutable. Calling such a closure also needs `let mut on_click`, otherwise E0596. Fixes: move the read after the last call, pass the counter in (`|c: &mut i32| *c += 1`), or keep the state in a struct whose method does the update.

code

rust · 8 lines
rust
fn main() {
    let mut clicks = 0;
    let on_click = |c: &mut i32| *c += 1; // borrows only while it runs
    on_click(&mut clicks);
    println!("clicks = {clicks}");
    on_click(&mut clicks);
    println!("clicks = {clicks}");
}

go deeper

for a junior

Recall that a closure which changes a variable keeps it borrowed mutably, and that its binding must be let mut.

for a middle

Explain that the borrow runs from creation to the closure's last use, read the three labels of E0502, and name the reorder and parameter fixes.

for a senior

Design handlers so state is passed in or owned by a struct with methods, and spot the move-on-a-Copy-counter fix that silently breaks the count.

for a principal

In an event system, set the rule for where mutable handler state lives so callbacks do not hold long borrows of shared locals.

## Where the borrow lives When a Rust closure's body assigns to an outside variable, rustc captures that variable by **mutable borrow**: the closure value contains a `&mut` to it. The closure is an ordinary value, so the borrow inside it lives as long as the closure value is still going to be used. Two facts decide when that is: - The borrow **starts when the closure is created**, at `let mut on_click = || clicks += 1;`, not at the first call. - Under **non-lexical lifetimes** (NLL) it ends at the closure's **last use**, which may be well before the end of the block. So between the first and the last call of `on_click`, `clicks` is exclusively borrowed by the closure. Any other use of `clicks` there, even a read, needs a second borrow, and the borrow rules forbid a shared borrow alongside a live mutable one. ## What rustc 1.99.1 prints ```rust let mut clicks = 0; let mut on_click = || clicks += 1; on_click(); println!("clicks = {clicks}"); // E0502 on_click(); ``` ```plaintext error[E0502]: cannot borrow `clicks` as immutable because it is also borrowed as mutable 3 | let mut on_click = || clicks += 1; | -- ------ first borrow occurs due to use of `clicks` in closure | | | mutable borrow occurs here 5 | println!("clicks = {clicks}"); | ^^^^^^ immutable borrow occurs here 6 | on_click(); | -------- mutable borrow later used here ``` The three labels map onto the model: the borrow is created at the closure, the read conflicts with it, and the later call is what keeps it alive. ## Why the binding needs `mut` too Calling a closure that mutates through a captured `&mut` requires mutable access to the closure value itself. With `let on_click = || clicks += 1;` rustc reports **E0596**, cannot borrow `on_click` as mutable, as it is not declared as mutable, and suggests `let mut on_click`. Which call trait that corresponds to belongs with the material on `Fn`, `FnMut` and `FnOnce`; here it is enough that the binding must be `mut`. ## The same rule for a reading closure A closure that only reads a variable holds a **shared** borrow, so it blocks writes instead of reads. `let show = || println!("{clicks}"); clicks += 1; show();` fails with **E0506**, cannot assign to `clicks` because it is borrowed. ## Fixes, from least to most restructuring 1. **Reorder.** Put the read after the closure's last call. NLL ends the borrow there, with no extra block needed. 2. **Pass the state in.** `let on_click = |c: &mut i32| *c += 1;` captures nothing; each call borrows `clicks` only for the call: `on_click(&mut clicks); println!("{clicks}"); on_click(&mut clicks);` compiles. The binding no longer needs `mut`. 3. **Give the state an owner with methods.** A `Counter` struct with `fn click(&mut self)` makes each borrow last one method call, which suits an event system that registers many handlers. 4. **Interior mutability**, a `Cell` the closure reads through a shared borrow, also compiles; when to reach for it is covered with `Cell` and `RefCell`. What does **not** help: | attempt | result | |---|---| | wrap the `println!` in its own `{ }` block | still E0502: the closure is used after the block, so its borrow is live | | add `move` | compiles, but the closure increments its own copy of the `i32`; the outside `clicks` stays 0 | | declare `clicks` as `mut` | it already is; the conflict is between two borrows, not mutability | ## Why this is the right rule The closure's `&mut clicks` is an ordinary mutable reference, and the guarantee that nothing else observes a value while a `&mut` to it is live is what lets rustc rule out data races and invalidated references. A closure is not an exception; it is a struct holding a reference, and the error is the same one a struct holding a `&mut i32` would produce. ## In an event system The pattern bites hardest where handlers are registered once and called many times. Suppose a UI loop owns `clicks` and registers `on_click` with a dispatcher that keeps it for the whole session: - The dispatcher holds the closure, so the closure's `&mut clicks` lives as long as the dispatcher does. - The status bar that wants to show `clicks` on every frame can no longer read it: every read is E0502. - Shortening the dispatcher's life is rarely possible, so reordering does not help either. The durable fix is to stop capturing the counter at all. Either the dispatcher owns the state and passes `&mut` to each handler as an argument, or the state lives in a struct that both the handler and the status bar reach through methods. Both make every borrow last one call, which is what the borrow checker can accept.

  • In Rust, does `on_click` still block reads of `clicks` if it is never called again after the read?
    No. Non-lexical lifetimes end the closure's borrow at its last use, so a read after the final call compiles even though `on_click` is still in scope. The error appears only when a call after the read keeps the borrow alive.
  • In Rust, why does adding `move` make the E0502 go away yet give the wrong count?
    `move` captures `clicks` by value, and an `i32` is `Copy`, so the closure gets its own copy and no borrow of the outer variable exists. The closure increments that copy; the outer `clicks` is never changed and still prints 0.
  • In Rust, does a closure that only reads `clicks` cause a similar error?
    Yes, in the opposite direction. It holds a shared borrow from creation to last use, so reads elsewhere are fine but assigning to `clicks` in between fails with E0506, cannot assign to `clicks` because it is borrowed.

  • The closure borrows clicks only while each call is running.
  • Putting the println! in its own block makes it legal between the two calls.
  • Adding move fixes it and the outer counter still goes up.
  • Declaring clicks as mut is enough; the closure binding needs no mut.
  • Rust forbids a closure from mutating a variable it captured.