Rust

E0501 Cannot Borrow as Immutable Fix

A closure that captures a mutable reference holds unique access to what that reference points at, for as long as the closure may still be called. Using the same reference in between - even just to read through it - is E0501. This guide works the shapes that produce it and matches each one to its repair: finish the closure first, hand the reference to the closure as a parameter, copy or read the value before the closure exists, or scope the closure so it is gone before the reference is used again.

Written November 29, 2026 · Tested with Rust 1.99.1 · 26 min read

By the end of this guide
  • The rule underneath: a live closure holds unique access to what it captured
  • How to read the diagnostic
  • The first failure: the captured reference passed to a second function
  • The second failure: the captured reference passed to a function that only reads

Written November 29, 2026

Tested with Rust 1.99.1

What this guide is

Error E0501 is a mutable variable being used while it is already captured by a closure. The error codes index opens with exactly that sentence, and its example is the shape this guide starts from: a function takes a: &mut i32, a closure captures a to pass it to one helper, and the function then passes a to a second helper before the closure is ever called - "cannot borrow *a as mutable because previous closure requires unique access". The index gives the three repairs this guide uses throughout: finish using the closure before using the captured variable, pass the variable as a parameter to the closure, or define the closure later.

One condition decides whether this error is the one that appears, and it is worth stating before any of the failures: in every E0501 shape here, the variable the closure captures is itself a reference - a &mut parameter, or a local binding that holds a &mut. The closure's capture is a borrow of borrowed content, and the compiler gives that conflict its own code. The same program shapes built over an owned variable do not produce E0501 at all: a closure capturing an owned x, v, or s and a use of that variable in between is E0502, because there the capture is an ordinary mutable borrow and the second use is an ordinary conflicting borrow. That owned-variable case is worked in the traps, side by side with this guide's first failures, because telling the two apart is the first step of the repair: the fixes below are sequenced around the closure, not around a pair of references.

The forms in this guide each reproduce E0501 with a small, complete program. Passing the captured reference to a second function that needs it mutably. Passing it to a function that only reads it. Printing through it. Calling a method on it - a vector's len - while the closure that pushes to the vector is still live. Reading one field of the struct it points at. And forming an explicit shared reborrow of it, &*a. Each failure is followed by its repair, and the repairs differ on purpose: the right one depends on whether the outside use needs the value before the closure runs, after it runs, or not through the reference at all.

Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the file names are the bare names shown on the command line.

The rule underneath: a live closure holds unique access to what it captured

A closure that mutates through a captured mutable reference needs unique access to the value behind that reference every time it is called. The compiler therefore treats the capture as live from the closure's definition until its last call: anywhere in that span, the captured reference may not be used again - not mutably, and not even immutably. That is the part that surprises: the outside use in most of this guide's failures only reads. Reading through a reference while a writer may still run would let the read observe a value the closure is about to change, and the borrow rules in References and Borrowing - one mutable reference, or any number of immutable ones, never both at once - apply to the closure's hold exactly as they apply to a named reference's hold.

The span is the leverage. A reference's scope runs from where it is introduced through the last time it is used, not to the end of the enclosing block - the Book states this for ordinary references, and the closure's hold follows the same shape: it ends at the closure's last call, or where the closure goes out of scope. Every repair in this guide works by moving the outside use outside that span, or by removing the capture from the closure so the span never starts. Finish calling the closure first, and the reference is free again. Scope the closure in a block, call it inside the block, and the reference is free after the block. Copy the value out before the closure is defined, and the outside use reads the copy, which no capture touches. Pass the reference in as a parameter at call time, and the closure captures nothing, so there is no span at all. Read the value before defining the closure, and the use is already complete when the span begins.

What never works is persuading the compiler that the outside use is harmless. A read is still a borrow, a method call that only inspects - len - is still a borrow, and a field read is still a borrow of the field's place. The diagnostic names the attempted borrow's mutability, not its risk: "as immutable" for the reads, "as mutable" for the second function that writes. Both wordings are the same error and take the same family of repairs.

How to read the diagnostic

The header names three things: the place that was borrowed (*a, a, or a.n - whatever the outside use touched), the mutability of the attempted borrow ("as immutable" or "as mutable"), and the reason - "because previous closure requires unique access". Below it, three spans lay out the timeline. The span on the closure's ||, labeled "closure construction occurs here" and "first borrow occurs due to use of *a in closure", marks where the hold began. The caret span, labeled "second borrow occurs here", marks the outside use that conflicts. And a span under the later call, labeled "first borrow later used here", is the proof that the hold was still live at the outside use - it is the line to check first, because if the closure is never called after the outside use, there is no error to repair, as the last trap shows.

That reading also separates this error from its neighbors before any repair starts. If the header says "closure requires unique access ... but it is already borrowed", the borrow came first and the closure second - that is E0500, the mirror image of this one. If there is no closure in the program at all, conflicting borrows are E0502. If the outside act is a plain use of a mutably borrowed value - arithmetic on it, not a borrow of it - the header is E0503. And if the outside act writes a new value into the borrowed place, the header is E0506, "cannot assign ... because it is borrowed". All four are worked in the traps.

The first failure: the captured reference passed to a second function

This is the error index's own example shape. bar captures a to hand it to inside_closure; before bar is called, foo hands the same a to outside_closure. The second hand-off is a mutable borrow of *a, and the closure's hold is still live because bar() runs after it:

Rust
fn inside_closure(x: &mut i32) { *x += 1; }
fn outside_closure(x: &mut i32) { *x += 10; }
fn foo(a: &mut i32) {
    let mut bar = || { inside_closure(a) };
    outside_closure(a);
    bar();
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
error[E0501]: cannot borrow `*a` as mutable because previous closure requires unique access
 --> a1.rs:5:21
  |
4 |     let mut bar = || { inside_closure(a) };
  |                   --                  - first borrow occurs due to use of `*a` in closure
  |                   |
  |                   closure construction occurs here
5 |     outside_closure(a);
  |                     ^ second borrow occurs here
6 |     bar();
  |     --- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0501`.

The repair the index prescribes first is to finish using the closure before using the captured variable: call bar() first, and a is free for the second function. The order of the two operations swaps, and nothing else changes:

Rust
fn inside_closure(x: &mut i32) { *x += 1; }
fn outside_closure(x: &mut i32) { *x += 10; }
fn foo(a: &mut i32) {
    let mut bar = || { inside_closure(a) };
    bar();
    outside_closure(a);
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
value is 12

The output is value is 12: the closure adds 1, the second function adds 10, and the caller's variable ends at 12 - the same total the failing order intended, reached in the order the borrow rules allow.

The second failure: the captured reference passed to a function that only reads

Making the second function read-only does not help. show takes &i32 - it cannot change anything - and the call is still a second borrow of *a inside the closure's span:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn show(x: &i32) { println!("seen is {x}"); }
fn foo(a: &mut i32) {
    let mut bar = || { bump(a) };
    show(a);
    bar();
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
error[E0501]: cannot borrow `*a` as immutable because previous closure requires unique access
 --> a2.rs:5:10
  |
4 |     let mut bar = || { bump(a) };
  |                   --        - first borrow occurs due to use of `*a` in closure
  |                   |
  |                   closure construction occurs here
5 |     show(a);
  |          ^ second borrow occurs here
6 |     bar();
  |     --- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0501`.

The header changes one word - "as immutable" - and nothing else. The repair here is the index's second prescription: pass the variable as a parameter to the closure instead of letting it capture. A closure that receives s: &mut i32 at call time holds nothing between calls, so show(a) may run first and the closure may be called with a afterward:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn show(x: &i32) { println!("seen is {x}"); }
fn foo(a: &mut i32) {
    let bar = |s: &mut i32| { bump(s) };
    show(a);
    bar(a);
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
seen is 1
value is 2

The output is seen is 1, then value is 2: the read sees the value before the closure's increment, and the increment still lands. This is the repair to reach for when the outside use genuinely has to happen first - the closure's design changes, not the call order.

The third failure: printing through the captured reference

No second function is needed. Printing a inside foo borrows a immutably to format it, and that borrow lands inside the span:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn foo(a: &mut i32) {
    let mut bar = || { bump(a) };
    println!("value is {a}");
    bar();
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
error[E0501]: cannot borrow `a` as immutable because previous closure requires unique access
 --> a3.rs:4:25
  |
3 |     let mut bar = || { bump(a) };
  |                   --        - first borrow occurs due to use of `*a` in closure
  |                   |
  |                   closure construction occurs here
4 |     println!("value is {a}");
  |                         ^ second borrow occurs here
5 |     bar();
  |     --- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0501`.

Note the place named in this header: a, not *a. Formatting the reference itself borrows the binding; the failures around it borrow through the reference, and the compiler names whichever place the outside use actually touched. The repair, when the value to print is the value before the closure runs, is to copy it out before the closure exists. *a is an i32, which is Copy, so the snapshot is a plain read taken while nothing is captured yet - after that, the print uses the snapshot and never touches a inside the span:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn foo(a: &mut i32) {
    let snapshot = *a;
    let mut bar = || { bump(a) };
    println!("value is {snapshot}");
    bar();
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
value is 1
value is 2

The output is value is 1, then value is 2: the snapshot preserves the pre-closure value for the print, and the caller's variable still receives the increment. For a value that is not Copy, the same repair reads through a clone taken before the closure is defined, or moves the print before the definition - the shape of the fix is identical: the read happens outside the span, on whichever side of it has the value the read needs.

The fourth failure: a method call on the captured reference

The captured reference does not have to arrive as a parameter. Here a is a local &mut Vec binding, the closure captures it to push, and the outside use is a.len() - a shared method call, as read-only as a method gets:

Rust
fn main() {
    let mut v = vec![1, 2];
    let a = &mut v;
    let mut bar = || { a.push(3); };
    println!("len is {}", a.len());
    bar();
}
Output
error[E0501]: cannot borrow `*a` as immutable because previous closure requires unique access
 --> a4.rs:5:27
  |
4 |     let mut bar = || { a.push(3); };
  |                   --   - first borrow occurs due to use of `*a` in closure
  |                   |
  |                   closure construction occurs here
5 |     println!("len is {}", a.len());
  |                           ^ second borrow occurs here
6 |     bar();
  |     --- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0501`.

A method call is a borrow of its receiver, so len is a second borrow of *a for the duration of the call, and that is enough. The repair is scoping: put the closure in a block, call it there, and let the block end the capture. After the block, a is usable again for the length the program wanted all along - now the length after the push:

Rust
fn main() {
    let mut v = vec![1, 2];
    let a = &mut v;
    {
        let mut bar = || { a.push(3); };
        bar();
    }
    println!("len is {}", a.len());
}
Output
len is 3

The output is len is 3: the push landed inside the block, and the len call after it reads the finished vector. Scoping is the repair when the closure's work is a self-contained step - once it has run, nothing needs it again, and the block makes that explicit to the compiler.

The fifth failure: reading a field through the captured reference

The outside use can be narrower than the whole value. a points at a Counter; the closure captures a to increment it through bump; the outside use reads only the field a.n:

Rust
struct Counter { n: i32 }
fn bump(c: &mut Counter) { c.n += 1; }
fn foo(a: &mut Counter) {
    let mut bar = || { bump(a) };
    println!("n is {}", a.n);
    bar();
}
fn main() { let mut c = Counter { n: 5 }; foo(&mut c); println!("n is {}", c.n); }
Output
error[E0501]: cannot borrow `a.n` as immutable because previous closure requires unique access
 --> a5.rs:5:25
  |
4 |     let mut bar = || { bump(a) };
  |                   --        - first borrow occurs due to use of `*a` in closure
  |                   |
  |                   closure construction occurs here
5 |     println!("n is {}", a.n);
  |                         ^^^ second borrow occurs here
6 |     bar();
  |     --- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0501`.

The header names the narrower place - a.n - and the conflict is unchanged: the field read is an immutable borrow of that field's place, inside the span of a closure that may rewrite the whole struct. The repair is the index's third prescription: define the closure later. The read moves before the definition, where no capture exists yet, and the closure is created only once the read is done:

Rust
struct Counter { n: i32 }
fn bump(c: &mut Counter) { c.n += 1; }
fn foo(a: &mut Counter) {
    println!("n is {}", a.n);
    let mut bar = || { bump(a) };
    bar();
}
fn main() { let mut c = Counter { n: 5 }; foo(&mut c); println!("n is {}", c.n); }
Output
n is 5
n is 6

The output is n is 5, then n is 6: the read sees the field's starting value, and the closure still increments it afterward. Defining later is the smallest repair in this guide - no call order changes, no copies - and it fits whenever the outside use needs the value as it was before the closure ran.

The sixth failure: an explicit shared reborrow of the captured reference

Writing the reborrow out by hand does not change its status. &*a is the most explicit immutable borrow Rust offers - a shared reference to what a points at - and it is still a second borrow inside the span:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn foo(a: &mut i32) {
    let mut bar = || { bump(a) };
    let r = &*a;
    println!("r is {r}");
    bar();
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
error[E0501]: cannot borrow `*a` as immutable because previous closure requires unique access
 --> a6.rs:4:13
  |
3 |     let mut bar = || { bump(a) };
  |                   --        - first borrow occurs due to use of `*a` in closure
  |                   |
  |                   closure construction occurs here
4 |     let r = &*a;
  |             ^^^ second borrow occurs here
5 |     println!("r is {r}");
6 |     bar();
  |     --- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0501`.

The caret span covers all of &*a, because the reborrow expression is the second borrow. The repair combines the snapshot idea with the reborrow's intent: take the copy first, and form the shared reference to the copy. r then borrows a local that no closure has captured, and it stays valid across the closure's call:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn foo(a: &mut i32) {
    let snapshot = *a;
    let r = &snapshot;
    println!("r is {r}");
    let mut bar = || { bump(a) };
    bar();
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
r is 1
value is 2

The output is r is 1, then value is 2: r reads the value as it was when the snapshot was taken, and the closure's increment lands on the caller's variable independently. The trade is the snapshot's usual one - r does not observe the closure's write - which is exactly right when the read needed the earlier value, and wrong when it needs the later one; in that case, finish the closure first and reborrow afterward instead.

The fixes in reach order

  • Finish using the closure before using the captured variable - the error index's first prescription, and the repair for the first failure. Call the closure for the last time, and every later use of the reference is free.
  • Pass the variable as a parameter to the closure - the index's second prescription, and the repair for the second failure. The closure captures nothing, so uses of the reference may stand anywhere outside its calls.
  • Define the closure later - the index's third prescription, and the repair for the fifth failure. Uses that need the pre-closure value move before the definition; the capture's span then starts after them.
  • Copy or clone the value out before defining the closure, and use the copy inside the span - the repair for the third and sixth failures. The copy is not captured, so reads of it never conflict.
  • Scope the closure in a block and call it inside the block - the repair for the fourth failure. The capture ends at the block's end even though the closure's owner continues.

Traps

Trap
The same shape over an owned variable - E0502, not E0501. Replace the &mut parameter with an owned local and the error changes code. inc captures the owned x mutably, and printing x in between draws the ordinary conflicting-borrow header, with "mutable borrow occurs here" where the E0501 transcripts say "closure construction occurs here":
Rust
fn main() {
    let mut x = 5;
    let mut inc = || { x += 1; };
    println!("value is {x}");
    inc();
}
Output
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
 --> n1_owned_closure.rs:4:25
  |
3 |     let mut inc = || { x += 1; };
  |                   --   - first borrow occurs due to use of `x` in closure
  |                   |
  |                   mutable borrow occurs here
4 |     println!("value is {x}");
  |                         ^ immutable borrow occurs here
5 |     inc();
  |     --- mutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.

The distinction matters because the repairs differ in emphasis: an E0502 between a closure and a use is repaired by reordering borrows, and the closure is just one borrow among others; an E0501 is specifically about a reference that was lent onward into a closure, and the parameter-passing and define-later repairs - changing what the closure is - are on the table. Check which variable the closure captured before choosing: a reference it was handed, or a value it owns the borrow of directly.

No closure at all - E0502 in both directions. The first failure's conflict with the closure removed is two named references. Mutable first, then immutable:

Rust
fn main() {
    let mut x = 5;
    let m = &mut x;
    let r = &x;
    println!("r is {r}");
    *m += 1;
}
Output
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
 --> n2_direct.rs:4:13
  |
3 |     let m = &mut x;
  |             ------ mutable borrow occurs here
4 |     let r = &x;
  |             ^^ immutable borrow occurs here
5 |     println!("r is {r}");
6 |     *m += 1;
  |     ------- mutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.

And immutable first, then mutable - the direction the short version of this error's name suggests, and still E0502:

Rust
fn main() {
    let mut x = 5;
    let r = &x;
    let m = &mut x;
    *m += 1;
    println!("r is {r}");
}
Output
error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable
 --> n3_reverse.rs:4:13
  |
3 |     let r = &x;
  |             -- immutable borrow occurs here
4 |     let m = &mut x;
  |             ^^^^^^ mutable borrow occurs here
5 |     *m += 1;
6 |     println!("r is {r}");
  |                     - immutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.

Neither direction produces E0501, because E0501 is not the code for "borrowed as immutable while borrowed as mutable" in general - it is the code for the closure-capture case of that conflict, where the first hold is a closure's capture of a reference. A search that lands on this guide from a plain two-reference error is in E0502's territory, and its repairs are the borrow-reordering ones.

The borrow was already live when the closure was defined - E0500, the mirror image. Here an immutable reference to the parameter exists first, and the closure that needs unique access comes second:

Rust
fn you_know_nothing(jon_snow: &mut i32) {
    let nights_watch = &jon_snow;
    let mut starks = || { *jon_snow = 3; };
    starks();
    println!("watch is {nights_watch}");
}
fn main() { let mut v = 1; you_know_nothing(&mut v); println!("value is {v}"); }
Output
error[E0500]: closure requires unique access to `*jon_snow` but it is already borrowed
 --> n5_borrowed_first.rs:3:22
  |
2 |     let nights_watch = &jon_snow;
  |                        --------- borrow occurs here
3 |     let mut starks = || { *jon_snow = 3; };
  |                      ^^   --------- second borrow occurs due to use of `*jon_snow` in closure
  |                      |
  |                      closure construction occurs here
4 |     starks();
5 |     println!("watch is {nights_watch}");
  |                         ------------ first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0500`.

The header reverses the story: "closure requires unique access to *jon_snow but it is already borrowed". In E0501 the closure is the previous hold and the outside use is the intruder; in E0500 the outside borrow is previous and the closure is the intruder. The repairs rhyme - end the first hold before starting the second - but which side moves depends on which error fired, and the header's word order is the tell.

A plain use of a mutably borrowed value - E0503. Not every conflict inside a borrow's span is a borrow. Using value in arithmetic while borrow holds it mutably is a use, not a second borrow, and it has its own code:

Rust
fn main() {
    let mut value = 3;
    let borrow = &mut value;
    let sum = value + 1;
    println!("sum is {sum}");
    println!("borrow is {borrow}");
}
Output
error[E0503]: cannot use `value` because it was mutably borrowed
 --> n4_use.rs:4:15
  |
3 |     let borrow = &mut value;
  |                  ---------- `value` is borrowed here
4 |     let sum = value + 1;
  |               ^^^^^ use of borrowed `value`
5 |     println!("sum is {sum}");
6 |     println!("borrow is {borrow}");
  |                          ------ borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0503`.

The separation is the verb in the header: "cannot use" for a use of the value itself, "cannot borrow" for forming another reference to it. E0501's outside acts are all borrows - calls, prints, method calls, reborrows - which is why they share one code despite looking different.

Assigning through the captured reference - E0506. Writing a new value into *a while the closure holds it is not a borrow either; it is an assignment to a borrowed place:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn foo(a: &mut i32) {
    let mut bar = || { bump(a) };
    *a = 10;
    bar();
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
error[E0506]: cannot assign to `*a` because it is borrowed
 --> n6_assign.rs:4:5
  |
3 |     let mut bar = || { bump(a) };
  |                   --        - borrow occurs due to use in closure
  |                   |
  |                   `*a` is borrowed here
4 |     *a = 10;
  |     ^^^^^^^ `*a` is assigned to here but it was already borrowed
5 |     bar();
  |     --- borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0506`.

The repair is the first fix again - finish the closure, then assign - but the diagnostic to expect is E0506's, and a fix aimed at borrow ordering alone will not describe what the compiler said.

The mutable borrow already finished - compiles. The borrow rules are about overlap, not about sequence. A mutable borrow whose last use comes before an immutable borrow starts is no conflict at all:

Rust
fn main() {
    let mut x = 5;
    let m = &mut x;
    *m += 1;
    let r = &x;
    println!("r is {r}");
}
Output
r is 6

The output is r is 6. This is the control case behind every repair in this guide: each fix works by arranging exactly this - two holds of the same value, in sequence, with no point where both are live.

The closure never called - compiles, with a warning. A closure that is defined but never used does not keep its capture live, because there is no later call for the hold to protect:

Rust
fn bump(x: &mut i32) { *x += 1; }
fn foo(a: &mut i32) {
    let bar = || { bump(a) };
    println!("value is {a}");
}
fn main() { let mut v = 1; foo(&mut v); println!("value is {v}"); }
Output
warning: unused variable: `bar`
 --> c2_unused_closure.rs:3:9
  |
3 |     let bar = || { bump(a) };
  |         ^^^ help: if this is intentional, prefix it with an underscore: `_bar`
  |
  = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default

warning: 1 warning emitted

Output
value is 1
value is 1

The output is value is 1, then value is 1: the print inside foo runs, no increment ever happens, and the compiler's only complaint is the unused variable. The practical reading is the contrapositive of the diagnostic's third span - E0501 needs the "first borrow later used here" line. If a program like the third failure compiles when the closure's call is deleted, the error was never the print; it was the print standing before a call that still had to happen.

Decision summary

  • The header is E0501 when three facts hold together: a closure has captured a variable, that variable is itself a reference (&mut parameter or local &mut binding), and the same reference is used again - by any borrow, mutable or immutable - before the closure's last call.
  • The three spans are the timeline: closure construction where the hold began, the caret at the outside use, and the later call proving the hold was live. The repair moves the outside use out of that span, or removes the capture.
  • "As immutable" in the header does not make the error milder or different: a read-only second function, a print, a len call, a field read, and an explicit &*a reborrow all fire the same code as a mutable second use.
  • Neighbors ruled out by the header before applying this guide's repairs: E0502 for the same shapes over an owned variable and for any closure-free pair of references, E0500 when the borrow predates the closure, E0503 for a plain use of a mutably borrowed value, E0506 for an assignment to the borrowed place.
  • Not an error at all: the two holds in sequence with no overlap - the first borrow finished before the second begins - and a closure that is never called after the outside use, or never called at all.

Checklist

  • Find the closure's last call first; every use of the captured reference before that line is inside the span, and every use after it is free.
  • Identify what the closure captured: a handed-on reference means E0501 repairs (finish, parameterize, define later, copy out, scope); an owned variable means E0502 repairs.
  • Decide what the outside use needs: the value before the closure runs (copy out, or define the closure later), the value after it runs (finish or scope the closure first), or the reference at call time only (pass it as a parameter).
  • Do not soften the outside use to make it pass - a read, a method call, and a field read are all borrows, and all fire the same error inside the span.
  • If the header names an assignment or a plain use rather than a borrow, stop: the error is E0506 or E0503 and the framing is different, even when the repair ends up similar.

Sources

  • Rust, Error codes index: E0501 - the definition of the error: a mutable variable is used but it is already captured by a closure - with the &mut i32 parameter example this guide's first failure follows, the explanation that the closure has borrowed the variable so it is not available until the closure goes out of scope, and the three prescriptions this guide follows: finish using the closure before using the captured variable, pass the variable as a parameter to the closure, or define the closure later.
  • The Rust Programming Language, References and Borrowing - the borrow rules underneath: one mutable reference or any number of immutable references to a value, never both at once; and the scope rule the repairs rely on - a reference's scope runs from where it is introduced through the last time it is used, so holds that do not overlap in use do not conflict.
  • Rust, Error codes index: E0500 - the mirror-image error separated in the traps: a borrowed variable was used by a closure - the borrow predates the closure that requires unique access.
  • Rust, Error codes index: E0502 - the neighboring error separated in the traps: a variable already borrowed with one mutability was borrowed again with a different mutability - the code for the same shapes over an owned variable and for closure-free reference pairs.
  • Rust, Error codes index: E0503 - the neighboring error separated in the traps: a value was used after it was mutably borrowed.
  • Rust, Error codes index: E0506 - the neighboring error separated in the traps: an attempt was made to assign to a borrowed value.

Keep Exploring