Rust

E0502 Cannot Borrow Fix

One value can be read through many shared borrows or changed through one mutable borrow, but never both at the same moment - and E0502 is the compiler naming the exact moment the two overlap. This guide separates the shapes that produce it and matches each one to the repair that ends the overlap: finish the first borrow, copy the value out, or split the work in two.

Written November 24, 2026 · Tested with Rust 1.99.1 · 35 min read

By the end of this guide
  • The rule underneath: one mutable borrow, or any number of shared borrows
  • How to read the diagnostic
  • The first failure: a shared borrow held across a mutable borrow
  • The second failure: a mutable borrow held across a shared borrow

Written November 24, 2026

Tested with Rust 1.99.1

What this guide is

Error E0502 is two borrows of opposite mutability alive at the same time on the same value. The error codes index defines it in one sentence: a variable already borrowed with a certain mutability, either mutable or immutable, was borrowed again with a different mutability. The header states the direction of the collision - "cannot borrow x as mutable because it is also borrowed as immutable" when the shared borrow came first, and "cannot borrow x as immutable because it is also borrowed as mutable" for the mirror - and in every family below the defect has the same three parts: a first borrow, a second borrow of the other mutability, and a later use that keeps the first borrow alive across the second. Remove the overlap and the error goes with it, which is why the fixes in this guide are only ever reorderings, copies, or splits.

The forms in this guide each reproduce E0502 with a small, complete program, and each creates the overlap in a different place. Two named references in sequence. The mirror pair, mutable first. A mutating method call while a reference is read later. A Vec growing while one of its elements is borrowed, and while an iterator over it is borrowed. Both borrows supplied as arguments to a single call. A shared borrow of a &mut parameter held across passing that parameter on mutably - the error index's own example shape. A whole value borrowed shared while one of its fields is borrowed mutably. And a closure whose capture keeps a shared borrow alive across a mutation.

Several neighboring results are not E0502 and are worked only in the traps and the decision summary. A method call that borrows its receiver mutably and one of its arguments shared - v.push(v.len()) - compiles, because that argument borrow is a two-phase borrow. Borrowing two different fields of one struct, one mutably and one shared, compiles, because the borrows are disjoint. A borrow whose last use comes before the opposing borrow compiles, because a borrow ends at its last use, not at the end of its block. split_at_mut compiles, because it hands out two mutable borrows over provably separate halves. A second mutable borrow is E0499, not E0502. Assigning to a borrowed value is E0506, moving a borrowed value is E0505, and mutating through a & reference is E0596.

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: one mutable borrow, or any number of shared borrows

The Rust Book's borrowing chapter states the restriction for mutable references directly: if you have a mutable reference to a value, you can have no other references to that value. The same chapter states the combined rule from the other side - readers do not expect the value to change out from under them, so a mutable reference cannot exist while an immutable one is live, while multiple immutable references are allowed because reading does not affect anyone else's reading. Put as one rule: at any moment a value has either any number of shared (&) borrows, or exactly one mutable (&mut) borrow, and never a mixture. E0502 is the mixed case. E0499, in the traps, is the two-mutable case.

The second half of the rule is when a borrow counts as alive. The Book states it as a scope rule: a reference's scope starts where it is introduced and continues through the last time that reference is used. A borrow that is never used again is already over, even if its variable is still in scope and its block has not closed - which is why the same three lines can fail or compile depending on where a println! sits. In the failing programs below - the one-call family of the sixth failure excepted, where the use is the call itself and section six gives its own repair - the later use is load-bearing: move that use above the second borrow, or delete it, and the program compiles unchanged in every other respect. The diagnostic marks that later use explicitly, with the span "borrow later used here", so the overlap the compiler is complaining about can always be read off the three spans together.

The fix follows from the rule rather than from the header's wording. Since the defect is an overlap in time, the repair is to end the overlap: use the first borrow for the last time before the second borrow begins (a reordering, or a block that confines the first borrow), copy the borrowed value out into an owned value and drop the borrow entirely (the right repair when the borrowed piece is a small Copy value such as one element or a length), or split the borrowed thing into disjoint pieces so each borrow covers a part the other does not touch (different fields, or split_at_mut on a slice). What never works is renaming, reordering declarations without moving the last use, or adding a scope around the second borrow while the first borrow's last use still sits after it - the overlap is between uses, not between declarations.

How to read the diagnostic

The header names the value, the attempted mutability, and the mutability already live: "cannot borrow s as mutable because it is also borrowed as immutable", or the mirror with the two mutabilities exchanged. Below it, three spans tell the whole story. One marks where the first borrow occurs - "immutable borrow occurs here" or "mutable borrow occurs here". One, underlined with carets on the second borrow, marks where the opposing borrow was attempted - "mutable borrow occurs here" or "immutable borrow occurs here". And one marks the use that keeps the first borrow alive across the attempt - "immutable borrow later used here" or "mutable borrow later used here". Reading the three together gives the repair directly: the first borrow's life has to end above the caret span, and the third span is the use that has to move, be copied out of, or go.

That third span is also the fastest way to tell this error from its neighbors. When there is no opposing-mutability pair at all - two mutable borrows report E0499, an assignment reports E0506, a move reports E0505, and a mutation attempted through a shared reference reports E0596 - the header names a different defect and the repair is different, worked in the traps. And when the program the diagnostic points at looks like this guide's families but compiles - the argument to a method call, two fields of one struct, a borrow already finished - there is no error to fix: the borrows are two-phase, disjoint, or sequential, and the traps work each of those.

The first failure: a shared borrow held across a mutable borrow

This is the Rust Book's own example shape. Two shared borrows are unremarkable - any number may coexist - and the mutable borrow that follows them would be legal on its own. What makes the program fail is the println! at the end: it uses r1 and r2 after r3 is created, so the shared borrows are still alive at the moment the mutable borrow is attempted:

Rust
fn main() {
    let mut s = String::from("hello");
    let r1 = &s;
    let r2 = &s;
    let r3 = &mut s;
    println!("{} {} {}", r1, r2, r3);
}
Terminal
$ rustc --edition 2021 fail_imm_then_mut.rs -o fail_imm_then_mut
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> fail_imm_then_mut.rs:5:14
  |
3 |     let r1 = &s;
  |              -- immutable borrow occurs here
4 |     let r2 = &s;
5 |     let r3 = &mut s;
  |              ^^^^^^ mutable borrow occurs here
6 |     println!("{} {} {}", r1, r2, r3);
  |                          -- immutable borrow later used here

error: aborting due to 1 previous error

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

The diagnostic names all three spans: the shared borrow at &s, the caret span at &mut s, and r1 used later in the println!. The repair the Book gives for this exact program is the one used here: move the last use of the shared borrows above the mutable borrow. Once r1 and r2 have been printed, their borrows are over, and r3 may take the value exclusively - after which it, not the original variable, is the name that can still change the string:

Rust
fn main() {
    let mut s = String::from("hello");
    let r1 = &s;
    let r2 = &s;
    println!("{} {}", r1, r2);
    let r3 = &mut s;
    r3.push_str(", world");
    println!("{}", r3);
}
Terminal
$ rustc --edition 2021 fix_imm_then_mut.rs -o fix_imm_then_mut
$ ./fix_imm_then_mut
hello hello
hello, world

The output is hello hello, then hello, world: the shared reads finish, then the mutable borrow appends and prints the changed value. Nothing was copied and no scope braces were needed - only the order of the uses changed.

The second failure: a mutable borrow held across a shared borrow

The mirror image. Here the mutable borrow comes first, and the shared borrow is the intruder: &s is attempted while m is still alive, and m is used in the final println!, after the shared borrow is created. The header reverses with the order - "cannot borrow s as immutable because it is also borrowed as mutable":

Rust
fn main() {
    let mut s = String::from("hello");
    let m = &mut s;
    let r = &s;
    println!("{} {}", r, m);
}
Terminal
$ rustc --edition 2021 fail_mut_then_imm.rs -o fail_mut_then_imm
error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
 --> fail_mut_then_imm.rs:4:13
  |
3 |     let m = &mut s;
  |             ------ mutable borrow occurs here
4 |     let r = &s;
  |             ^^ immutable borrow occurs here
5 |     println!("{} {}", r, m);
  |                          - mutable borrow later used here

error: aborting due to 1 previous error

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

The mutable borrow is the one that has to finish first this time. Confining it to a block makes its end unmistakable: inside the block it appends and prints, the block closes, and only then is the shared borrow taken. A block is not what ends the borrow - the last use inside it does - but wrapping a borrow that must end early is the clearest way to keep later edits from quietly extending it again:

Rust
fn main() {
    let mut s = String::from("hello");
    {
        let m = &mut s;
        m.push_str(", world");
        println!("{}", m);
    }
    let r = &s;
    println!("{}", r);
}
Terminal
$ rustc --edition 2021 fix_mut_then_imm.rs -o fix_mut_then_imm
$ ./fix_mut_then_imm
hello, world
hello, world

The output is hello, world twice: once through the mutable borrow inside the block, and once through the shared borrow after it. The two borrows cover the same value at different times, which is all the rule ever required.

The third failure: a mutating method call while a reference is live

No second reference is written in this program, and it fails anyway. push_str takes &mut self, so calling it on s is a mutable borrow of s - a borrow created by the method call itself. The Rust Reference on expressions lists the left operand of a method call among the expressions that are implicitly borrowed, which is where that borrow comes from. The shared borrow in r is used after the call, so the call's mutable borrow lands inside r's life:

Rust
fn main() {
    let mut s = String::from("hello");
    let r = &s;
    s.push_str(", world");
    println!("{}", r);
}
Terminal
$ rustc --edition 2021 fail_push_str.rs -o fail_push_str
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> fail_push_str.rs:4:5
  |
3 |     let r = &s;
  |             -- immutable borrow occurs here
4 |     s.push_str(", world");
  |     ^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{}", r);
  |                    - immutable borrow later used here

error: aborting due to 1 previous error

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

Since the call site does not look like a borrow, this is the family programmers most often meet inside larger functions: a helper returns a reference, the value is then adjusted, and the reference is read at the end. The repair here reads what it needs out of the shared borrow first - the length, a Copy value - inside a block, and mutates only after the block closes. The shared borrow itself is never used again:

Rust
fn main() {
    let mut s = String::from("hello");
    let len = {
        let r = &s;
        r.len()
    };
    s.push_str(", world");
    println!("{} {}", len, s);
}
Terminal
$ rustc --edition 2021 fix_push_str.rs -o fix_push_str
$ ./fix_push_str
5 hello, world

The output is 5 hello, world: the length was taken while the shared borrow was the only borrow, and the append happened after it ended. When the value needed from a borrow is small and Copy, copying it out is usually a shorter repair than restructuring the code around the borrow.

The fourth failure: a vector grows while an element is borrowed

first borrows one element of v, and push borrows all of v mutably - it may have to move every element to a larger allocation, which is exactly the change a live element reference cannot survive. The borrow in the diagnostic is of v, not of the element alone, so borrowing a different element, or writing through an index, would not separate the two: any growth of the vector overlaps any borrow of its contents:

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    let first = &v[0];
    v.push(4);
    println!("{}", first);
}
Terminal
$ rustc --edition 2021 fail_vec_push.rs -o fail_vec_push
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> fail_vec_push.rs:4:5
  |
3 |     let first = &v[0];
  |                  - immutable borrow occurs here
4 |     v.push(4);
  |     ^^^^^^^^^ mutable borrow occurs here
5 |     println!("{}", first);
  |                    ----- immutable borrow later used here

error: aborting due to 1 previous error

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

The element here is an i32, so the clean repair is to stop borrowing it: indexing without the & copies the element out, no borrow survives, and push is free to reallocate. The printed value is the copy, taken before the push - if the program needed the element's value after growth, it would re-index the vector rather than keep a reference into storage that may have moved:

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    let first = v[0];
    v.push(4);
    println!("{} {:?}", first, v);
}
Terminal
$ rustc --edition 2021 fix_vec_push.rs -o fix_vec_push
$ ./fix_vec_push
1 [1, 2, 3, 4]

The output is 1 [1, 2, 3, 4]: the copied first element, then the grown vector. For a non-Copy element the same family takes a different form of the same repair - finish every use of the element reference before the push, or clone the element - but the overlap to remove is identical.

The fifth failure: a vector grows while an iterator is borrowed

An iterator over a slice is a shared borrow of the whole vector for as long as the iterator can still be used. v.iter() therefore holds v borrowed from its creation until the loop finishes consuming it, and the push in between is a mutable borrow attempted inside that span - the same collision as the previous family, with the iterator, rather than a named reference, as the borrow that stays alive:

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    let iter = v.iter();
    v.push(4);
    for x in iter {
        println!("{}", x);
    }
}
Terminal
$ rustc --edition 2021 fail_iter_push.rs -o fail_iter_push
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> fail_iter_push.rs:4:5
  |
3 |     let iter = v.iter();
  |                - immutable borrow occurs here
4 |     v.push(4);
  |     ^^^^^^^^^ mutable borrow occurs here
5 |     for x in iter {
  |              ---- immutable borrow later used here

error: aborting due to 1 previous error

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

Naming the borrow differently does not change its span: a for loop over v.iter(), an iterator stored in a variable, and an iterator adapter chain all keep the underlying shared borrow alive until their last possible use. The repair is to let the iteration actually finish before the mutation. Here the iteration is a sum, consumed on the spot, so by the next line no borrow remains and the push proceeds:

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    let sum: i32 = v.iter().sum();
    v.push(4);
    println!("{} {:?}", sum, v);
}
Terminal
$ rustc --edition 2021 fix_iter_push.rs -o fix_iter_push
$ ./fix_iter_push
6 [1, 2, 3, 4]

The output is 6 [1, 2, 3, 4]: the sum of the original three elements, then the vector with the fourth appended. When the iteration's result is needed in full - a collected list, a maximum, a count - collecting or reducing it first is the same repair: the borrow ends when the consuming call returns.

The sixth failure: both borrows passed to one call

A single call can create the whole collision by itself. show(&x, &mut x) takes a shared borrow of x for its first argument and a mutable borrow of the same x for its second, and both must be alive for the duration of the call - there is no ordering inside the argument list that sequences them, because arguments are not finished one at a time the way statements are. The diagnostic's spans are compressed into the one line, and its third span reads differently from the other families: "immutable borrow later used by call":

Rust
fn show(a: &i32, b: &mut i32) {
    println!("{} {}", a, b);
}
fn main() {
    let mut x = 5;
    show(&x, &mut x);
}
Terminal
$ rustc --edition 2021 fail_two_args.rs -o fail_two_args
error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable
 --> fail_two_args.rs:6:14
  |
6 |     show(&x, &mut x);
  |     ---- --  ^^^^^^ mutable borrow occurs here
  |     |    |
  |     |    immutable borrow occurs here
  |     immutable borrow later used by call

error: aborting due to 1 previous error

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

Because the overlap lasts exactly as long as the call, reordering statements cannot repair this shape - the two borrows have to be of different values, or the call has to be split so the shared read is copied out before the mutable borrow is taken. Here the two arguments were never required to be the same value, so the mutable borrow is given a value of its own:

Rust
fn show(a: &i32, b: &mut i32) {
    println!("{} {}", a, b);
}
fn main() {
    let x = 5;
    let mut y = 6;
    show(&x, &mut y);
    println!("{} {}", x, y);
}
Terminal
$ rustc --edition 2021 fix_two_args.rs -o fix_two_args
$ ./fix_two_args
5 6
5 6

The output is 5 6 twice: once inside show, once after it. When a call genuinely needs a shared view and a mutable view derived from one value, the standard form of this repair is to copy or clone the shared view's needed data before the call, and pass the copy - the call then holds no two borrows of one value.

The seventh failure: a shared borrow of a parameter held across a mutable reborrow

This is the error codes index's own example shape, adapted so it runs as a complete program: the index's bar has an empty body and there is no main, while here bar increments through its parameter and main supplies the value, so the fixed version below has output to show. foo receives a as a &mut i32. Taking y = &a borrows through that parameter shared, and y is printed after the next line - so when bar(a) passes a on, which needs it mutably, the shared borrow is still alive. The header names *a, the value behind the parameter, rather than a local variable, but the three-part defect is unchanged: first borrow, opposing borrow, later use:

Rust
fn bar(x: &mut i32) {
    *x += 1;
}
fn foo(a: &mut i32) {
    let y = &a;
    bar(a);
    println!("{}", y);
}
fn main() {
    let mut v = 5;
    foo(&mut v);
    println!("{}", v);
}
Terminal
$ rustc --edition 2021 fail_param_reborrow.rs -o fail_param_reborrow
error[E0502]: cannot borrow `*a` as mutable because it is also borrowed as immutable
 --> fail_param_reborrow.rs:6:5
  |
5 |     let y = &a;
  |             -- immutable borrow occurs here
6 |     bar(a);
  |     ^^^^^^ mutable borrow occurs here
7 |     println!("{}", y);
  |                    - immutable borrow later used here

error: aborting due to 1 previous error

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

The index's own prescription is to ensure there are no other references to the variable before accessing it with a different mutability, and its fixed example applies the same reordering this program uses: the mutable pass happens first, and the shared borrow is taken only afterwards, for the print. No borrow is copied or scoped - the shared borrow simply starts later, after the last mutable use instead of before it:

Rust
fn bar(x: &mut i32) {
    *x += 1;
}
fn foo(a: &mut i32) {
    bar(a);
    let y = &a;
    println!("{}", y);
}
fn main() {
    let mut v = 5;
    foo(&mut v);
    println!("{}", v);
}
Terminal
$ rustc --edition 2021 fix_param_reborrow.rs -o fix_param_reborrow
$ ./fix_param_reborrow
6
6

The output is 6 twice: bar increments the value to 6 through the mutable reborrow, and the shared borrow taken afterwards reads the incremented value - the opposite order from the failing program, where the print would have read the value across the mutation.

The eighth failure: a whole value borrowed while a field is borrowed mutably

whole borrows all of p, and a borrow of the whole covers every field - so &mut p.x, a borrow of one part, still overlaps it. The header names the smaller place, p.x, because that is the borrow being attempted, but the conflict is with the whole-value borrow, whose later use is the read of whole.y in the final line. Borrowing a part does not narrow a borrow of the whole that already exists:

Rust
struct Point { x: i32, y: i32 }
fn main() {
    let mut p = Point { x: 1, y: 2 };
    let whole = &p;
    let mx = &mut p.x;
    *mx += 10;
    println!("{} {}", whole.y, mx);
}
Terminal
$ rustc --edition 2021 fail_whole_field.rs -o fail_whole_field
error[E0502]: cannot borrow `p.x` as mutable because it is also borrowed as immutable
 --> fail_whole_field.rs:5:14
  |
4 |     let whole = &p;
  |                 -- immutable borrow occurs here
5 |     let mx = &mut p.x;
  |              ^^^^^^^^ mutable borrow occurs here
6 |     *mx += 10;
7 |     println!("{} {}", whole.y, mx);
  |                       ------- immutable borrow later used here

error: aborting due to 1 previous error

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

The disjointness that would have saved this program has to be established from the start: borrow fields, not the whole, and the compiler tracks field borrows separately - the traps show a mutable field borrow and a shared field borrow of two different fields compiling in one program. Here the whole-value read needed only y, an i32, so it is copied out first and no whole-value borrow is ever taken; the mutable borrow of x then stands alone:

Rust
struct Point { x: i32, y: i32 }
fn main() {
    let mut p = Point { x: 1, y: 2 };
    let y = p.y;
    let mx = &mut p.x;
    *mx += 10;
    println!("{} {}", y, mx);
}
Terminal
$ rustc --edition 2021 fix_whole_field.rs -o fix_whole_field
$ ./fix_whole_field
2 11

The output is 2 11: the copied y, and x after the increment through its mutable borrow. The general form of the repair is to replace every whole-value borrow with the field borrows - or field copies - the code actually uses, so the borrow checker can see the disjointness the programmer intended.

The ninth failure: a closure capture held across a mutation

A closure that reads a variable captures it by shared borrow, and that capture borrow lasts as long as the closure can still be called. get_len reads s, so it holds s borrowed from its definition until its call on the last line - and the push_str between the two is a mutable borrow inside that span. The diagnostic says so in its own wording: the first span reads "first borrow occurs due to use of s in closure". No reference variable appears anywhere in the program:

Rust
fn main() {
    let mut s = String::from("hello");
    let get_len = || s.len();
    s.push_str(", world");
    println!("{}", get_len());
}
Terminal
$ rustc --edition 2021 fail_closure_push.rs -o fail_closure_push
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> fail_closure_push.rs:4:5
  |
3 |     let get_len = || s.len();
  |                   -- - first borrow occurs due to use of `s` in closure
  |                   |
  |                   immutable borrow occurs here
4 |     s.push_str(", world");
  |     ^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{}", get_len());
  |                    ------- immutable borrow later used here

error: aborting due to 1 previous error

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

Closures make borrow spans easy to underestimate, because the borrow is created by a use inside a body that may run much later. The repairs are the familiar ones applied to the closure instead of a reference: call the closure for the last time before mutating, drop it, or - as here - call it inside a block and keep only its result, so the capture borrow ends with the block and the mutation follows a finished borrow:

Rust
fn main() {
    let mut s = String::from("hello");
    let len = {
        let get_len = || s.len();
        get_len()
    };
    s.push_str(", world");
    println!("{} {}", len, s);
}
Terminal
$ rustc --edition 2021 fix_closure_push.rs -o fix_closure_push
$ ./fix_closure_push
5 hello, world

The output is 5 hello, world: the length from the closure's single call, then the string after the append. Keeping only the result rather than the closure is the copy-out repair in closure form - what survives the block is a usize, not a borrow.

The fixes in reach order

  • Move the first borrow's last use above the second borrow. The cheapest repair, and the right one whenever both borrows are genuinely needed: find the "borrow later used here" span and move that use - or the whole second borrow - until the two spans no longer overlap.
  • Confine the first borrow to a block. The same reordering made structural: everything that uses the first borrow goes inside braces, and the opposing borrow is taken after the closing brace.
  • Copy the borrowed value out. When what is read through the first borrow is a Copy value - an element, a length, a field - take the copy and let the borrow end immediately; no reference survives to overlap anything.
  • Finish the consuming call first. Iterators, sums, collects, and closure calls all hold their borrows until they return; letting them return is what ends the borrow.
  • Split the value into disjoint parts. Different fields, or split_at_mut on a slice: two borrows the compiler can prove cover different storage do not overlap, whichever mutabilities they have.
  • Pass different values, or a copy, to the call. When both borrows are arguments of one call, no reordering inside the call exists; one argument must become a copy or another value.

Traps

  • A method call whose argument is a temporary shared borrow that only produces a value - v.len() producing a usize - compiles alongside the mutable receiver borrow; it is not this guide's sixth family. A shared reference passed as an argument, which stays alive for the whole call, is different: a method taking &mut self called as c.f(&c.v) fails with E0502, because that argument borrow does overlap the active mutable borrow. In v.push(v.len()), the mutable borrow of v for the receiver and the shared borrow of v for the argument coexist by design: a two-phase borrow begins the mutable borrow in a reserved, shared-like phase while the arguments are evaluated, and activates it only for the call itself. The argument borrow therefore never overlaps an active mutable borrow:
Rust
fn main() {
    let mut v = vec![1, 2, 3];
    v.push(v.len() as i32);
    println!("{:?}", v);
}
Terminal
$ rustc --edition 2021 trap_two_phase.rs -o trap_two_phase
$ ./trap_two_phase
[1, 2, 3, 3]
Trap
The output is [1, 2, 3, 3]: the length, 3, was read as the value to push, and then the push happened. The contrast with the sixth family is the position of the borrows: two-phase borrows exist for the receiver-and-argument shape of a method call, not for two independent arguments of a free function, and not for two statements - writing the same idea as let n = v.len(); held across a later use, then v.push(n), is the ordinary sequential case, and holding &v in a named variable across the push is the third family, E0502. - Borrowing two different fields of one struct at once, one mutably and one shared, compiles. Field borrows are tracked per field, so &mut p.x and &p.y are borrows of disjoint storage and may overlap freely - the disjointness the eighth family lacked, because there the first borrow was of the whole struct:
Rust
struct Point { x: i32, y: i32 }
fn main() {
    let mut p = Point { x: 1, y: 2 };
    let a = &mut p.x;
    let b = &p.y;
    *a += 10;
    println!("{} {}", a, b);
}
Terminal
$ rustc --edition 2021 trap_disjoint_fields.rs -o trap_disjoint_fields
$ ./trap_disjoint_fields
11 2

The output is 11 2: x incremented through its mutable borrow while y was read through its shared borrow, in the same span of code. The rule is about places, not variables in the abstract: one variable can host several simultaneous borrows, provided each borrow's place is separate from every opposing borrow's place. The same principle inside a slice is split_at_mut, below. - A shared borrow followed by a mutable borrow of the same value compiles when the shared borrow is never used after the mutable borrow begins. This is the first family with its println! moved up - the borrow ends at its last use, so nothing overlaps, even though both borrows sit in the same block and the shared variable is still in scope:

Rust
fn main() {
    let mut s = String::from("hello");
    let r = &s;
    println!("{}", r);
    let m = &mut s;
    m.push_str(", world");
    println!("{}", m);
}
Terminal
$ rustc --edition 2021 trap_nll_ends.rs -o trap_nll_ends
$ ./trap_nll_ends
hello
hello, world

The output is hello, then hello, world. Programmers arriving from pre-2018 Rust, or from explanations that tie a borrow to its enclosing block, expect this to fail; under the current checker the block is not the unit, the last use is. The practical consequence cuts both ways: adding a later use of an old reference - a debug print at the end of a function is the classic case - can turn compiling code into E0502 without any borrow being added. - split_at_mut hands out two mutable borrows of one slice at once, and compiles. It is a function, not a borrow expression: it takes the one mutable borrow and divides the slice into two halves the implementation guarantees do not overlap, so the two results are disjoint places in the sense of the field trap above:

Rust
fn main() {
    let mut v = vec![1, 2, 3, 4];
    let (left, right) = v.split_at_mut(2);
    left[0] += 10;
    right[0] += 30;
    println!("{:?} {:?}", left, right);
}
Terminal
$ rustc --edition 2021 trap_split_at_mut.rs -o trap_split_at_mut
$ ./trap_split_at_mut
[11, 2] [33, 4]

The output is [11, 2] [33, 4]: each half was written through its own mutable borrow while the other was live. Trying to obtain the same pair by indexing - two &mut v[..] borrows, or the element borrow of the fourth family held across a write - is E0502 or E0499, because the borrow checker cannot prove two index expressions disjoint; split_at_mut exists precisely to carry that proof. - A second mutable borrow while the first is still used later is E0499, not E0502. The mutabilities match, so the defect is not a mixture but a duplication - the header says "more than once at a time" rather than "also borrowed as" anything:

Rust
fn main() {
    let mut s = String::from("hello");
    let r1 = &mut s;
    let r2 = &mut s;
    println!("{} {}", r1, r2);
}
Terminal
$ rustc --edition 2021 trap_e0499.rs -o trap_e0499
error[E0499]: cannot borrow `s` as mutable more than once at a time
 --> trap_e0499.rs:4:14
  |
3 |     let r1 = &mut s;
  |              ------ first mutable borrow occurs here
4 |     let r2 = &mut s;
  |              ^^^^^^ second mutable borrow occurs here
5 |     println!("{} {}", r1, r2);
  |                       -- first borrow later used here

error: aborting due to 1 previous error

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

The repair is the same family of moves - finish the first mutable borrow before taking the second - but the code matters for the search: a program failing with two mutable borrows is governed by the one-mutable rule alone, and reading this guide's mixed-borrow families will not show its shape. - Assigning to a value while it is borrowed is E0506, not E0502. Assignment is not spelled as a borrow in the source, and the compiler does not report it as one: the header reads "cannot assign to x because it is borrowed", with no mutability pairing at all. (The warning below the error rides along because the assigned value is never read before the program ends; it is not part of the error.)

Rust
fn main() {
    let mut x = 5;
    let r = &x;
    x = 6;
    println!("{}", r);
}
Terminal
$ rustc --edition 2021 trap_assign_borrowed.rs -o trap_assign_borrowed
error[E0506]: cannot assign to `x` because it is borrowed
 --> trap_assign_borrowed.rs:4:5
  |
3 |     let r = &x;
  |             -- `x` is borrowed here
4 |     x = 6;
  |     ^^^^^ `x` is assigned to here but it was already borrowed
5 |     println!("{}", r);
  |                    - borrow later used here

warning: value assigned to `x` is never read
 --> trap_assign_borrowed.rs:4:5
  |
4 |     x = 6;
  |     ^^^^^
  |
  = help: maybe it is overwritten before being read?
  = note: `#[warn(unused_assignments)]` (part of `#[warn(unused)]`) on by default

error: aborting due to 1 previous error; 1 warning emitted

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

The distinction is mechanical: a &mut taken explicitly, or a method call needing &mut self, reports E0502 against a live shared borrow; a plain = reports E0506 against any live borrow, shared or mutable. Both are repaired by ending the borrow first, but a search on this guide's code will not find an assignment problem. - Moving a value while it is borrowed is E0505, not E0502. A move is neither a shared nor a mutable borrow, so there is no mutability mixture to report; the header names the move itself:

Rust
fn main() {
    let s = String::from("hello");
    let r = &s;
    let t = s;
    println!("{} {}", r, t);
}
Terminal
$ rustc --edition 2021 trap_move_borrowed.rs -o trap_move_borrowed
error[E0505]: cannot move out of `s` because it is borrowed
 --> trap_move_borrowed.rs:4:13
  |
2 |     let s = String::from("hello");
  |         - binding `s` declared here
3 |     let r = &s;
  |             -- borrow of `s` occurs here
4 |     let t = s;
  |             ^ move out of `s` occurs here
5 |     println!("{} {}", r, t);
  |                       - borrow later used here
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let r = &s.clone();
  |               ++++++++

error: aborting due to 1 previous error

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

The help the compiler prints - cloning the value so the reference points at the clone - is one repair; the other is the familiar one, ending the borrow before the move. Either way the code is E0505, and it belongs with the move errors, not with this guide. - Mutating through a shared reference is E0596, not E0502. Here there is only one borrow in the program - the &String parameter - and the defect is its mutability, not an overlap: nothing else borrows the string at all:

Rust
fn change(some_string: &String) {
    some_string.push_str(", world");
}
fn main() {
    let s = String::from("hello");
    change(&s);
}
Terminal
$ rustc --edition 2021 trap_e0596.rs -o trap_e0596
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
 --> trap_e0596.rs:2:5
  |
2 |     some_string.push_str(", world");
  |     ^^^^^^^^^^^ `some_string` is a `&` reference, so it cannot be borrowed as mutable
  |
help: consider changing this to be a mutable reference
  |
1 | fn change(some_string: &mut String) {
  |                         +++

error: aborting due to 1 previous error

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

The header reads "cannot borrow *some_string as mutable, as it is behind a & reference", and its help gives the repair: change the parameter to &mut String. Compare the third family, where push_str also fails - but there a second, live borrow exists, the code is E0502, and changing a signature would do nothing; ending the overlap is the only repair. Which of the two codes a push_str failure carries is decided entirely by whether another borrow is alive at the call.

Decision summary

  • The header says "cannot borrow x as mutable because it is also borrowed as immutable" (E0502), with a named shared reference used later: move that reference's last use above the mutable borrow, confine it to a block, or copy out what it reads.
  • The header is the mirror - "cannot borrow x as immutable because it is also borrowed as mutable" (E0502): the mutable borrow must finish first; confine it, or take the shared borrow after its last use.
  • The header is E0502 and the caret span sits on a method call - push_str, push, sort, a call on a vector or a string: the call is the mutable borrow; end, copy out of, or finish the shared borrow, iterator, or closure capture that is used after it.
  • The header is E0502 and both spans sit inside one call's argument list: the call holds both borrows for its whole duration - pass a copy or a different value for one argument.
  • The header names *a rather than a local (E0502): a parameter is borrowed both ways inside the function - reorder so the shared borrow of the parameter starts after its last mutable use.
  • The header names a field, p.x, while the first span is a borrow of the whole p (E0502): replace the whole-value borrow with the field reads actually needed, copied out or borrowed per field.
  • A mutable receiver with a shared argument from the same value - v.push(v.len()) - compiles: two-phase borrow, no error.
  • Two fields of one struct borrowed at once, in either mutability mixture, and the program compiles: disjoint field borrows, no error. Two halves from split_at_mut compile for the same reason.
  • A shared borrow, a mutation, and no use of the borrow after the mutation, and the program compiles: the borrow ended at its last use, no error.
  • The header says "cannot borrow as mutable more than once at a time" (E0499): two mutable borrows - finish the first before taking the second.
  • The header says "cannot assign to x because it is borrowed" (E0506): an assignment, not a borrow - end the borrow before assigning.
  • The header says "cannot move out of s because it is borrowed" (E0505): a move, not a borrow - end the borrow before moving, or clone.
  • The header says "as it is behind a & reference" (E0596): one borrow of the wrong mutability and no overlap - change the reference to &mut at its definition.

Checklist

  • The three spans read together before anything is moved: where the first borrow occurs, where the opposing borrow was attempted, and which later use keeps the first borrow alive.
  • The later use identified by name - that use, and nothing else, is what extends the first borrow across the attempt; a borrow with no later use is already over.
  • Decided which borrow the program needs second, and ended the other one first - by moving its last use, by a block, or by copying the value it reads.
  • Method calls, iterators, and closure captures counted as borrows: a push, a sort, an iterator that will still be consumed later, and a closure that will still be called later each hold a borrow until that later use. An iterator or closure with no later use holds no borrow - like any borrow, it ends at its last use.
  • Whole-value borrows checked against field borrows: a borrow of the whole covers every field, so field-level disjointness has to be set up from the first borrow, not the second.
  • One-call collisions handled at the argument list: a copy or a different value, never a reordering inside the call.
  • Neighbors ruled out by the header before applying this guide's repairs: E0499 for two mutable borrows, E0506 for assignment, E0505 for a move, E0596 for mutation through a &.
  • After the repair, the program compiled and run, with the output showing both operations - the read through the first borrow and the change through the second - happening in their new order.

Sources

  • Rust, Error codes index: E0502 - the definition of the error: a variable already borrowed with a certain mutability, either mutable or immutable, was borrowed again with a different mutability - with the foo and bar example over a &mut i32 parameter, and the prescription to ensure there are no other references to the variable before trying to access it with a different mutability, and the reordered version of the same example as its fix.
  • The Rust Programming Language, References and Borrowing - the borrowing rules this guide rests on: a mutable reference excludes every other reference to the same value; a mutable reference cannot coexist with an immutable one, while multiple immutable references are allowed because readers cannot affect each other's reading; the two-shared-and-one-mutable example that fails with E0502 and the same program passing once the shared references' last use precedes the mutable reference; and the scope rule that a reference's scope runs from its introduction through the last time it is used.
  • The Rust Reference, Expressions - the place- and value-expression rules behind the method-call families: the left operand of a method call is among the expressions that are implicitly borrowed, which is why a call such as push_str or push takes a borrow of its receiver without any & or &mut appearing at the call site.

Keep Exploring