Rust

Fix Rust E0502 "cannot borrow as mutable because it is also borrowed as immutable" — End the First Borrow, Split the Work, or Restructure

A reader is still holding the value when a writer asks for it. This guide separates the three ways that overlap happens — a borrow kept in a variable, a borrow held by a loop, and a borrow that only looks like it overlaps — and matches each one to its repair: finish with the first borrow before mutating, split the collection so the two accesses touch different parts, return an owned value instead of holding a reference across the mutation, and clone only when copying is the honest price.

Written November 22, 2026 · Tested with Rust 1.99.0 · 26 min read

By the end of this guide
  • The rule underneath: one writer, or any number of readers, never both at once
  • The first failure: a shared borrow held in a variable, then a mutation
  • The case that now compiles: the borrow whose last use comes first
  • The second failure: iterating a collection while mutating it

Written November 22, 2026

Tested with Rust 1.99.0

What this guide is

Error E0502 has one sentence at its center: a value cannot be borrowed as mutable while it is also borrowed as immutable. In plain terms, someone is still reading the value — through a shared reference, written &T — at the moment other code asks to change it, through a mutable reference, written &mut T, or through a method such as push or sort that needs one. The compiler refuses, not because the two operations sit near each other in the file, but because they overlap in time: the shared borrow is still needed later, so it is still alive when the mutable borrow is requested.

That overlap is the whole diagnosis, and it is also the whole repair. Every correct fix for E0502 does exactly one of three things. It ends the first borrow before the mutation, so the two borrows no longer overlap. It splits the work, so the reading and the writing touch provably different parts of the data and the compiler can allow both at once. Or it restructures the code, so no reference is held across the mutation at all — a value is computed and returned, and the mutation works on owned data. A fourth move, cloning the borrowed data so the original is free, always works and is almost always the wrong first answer; it appears last in this guide, priced honestly.

This guide works through the error in the order that separates its causes. First, the canonical form: a shared borrow stored in a variable, then a mutation, then a later use of the variable that keeps the borrow alive across the mutation. Second, the surprise that confuses most readers meeting this error today: the near-identical program in which the borrow's last use comes before the mutation compiles cleanly, because a borrow lives only until its last use, not until the end of its scope. Third, the loop form, where iterating over a collection holds the shared borrow for the entire loop body. Fourth, the method-call form that compiles — v.push(v.len()) — and the method-call form that does not, because two-phase borrows cover a narrow pattern and nothing wider. Then the fixes, in reach order, a section on the two silencing traps — cloning everything and moving the check to runtime with RefCell — a decision table, and a checklist.

Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the full file path in the location line is shortened to the file name; every other character is exactly as the compiler printed it.

The rule underneath: one writer, or any number of readers, never both at once

Rust allows a value to be borrowed in exactly two configurations at any one moment. It may have any number of shared borrows, &T, all reading. Or it may have exactly one mutable borrow, &mut T, reading and writing alone. What it may never have is a mix: one mutable borrow alongside any other borrow, shared or mutable. The Rust Reference states the shared side this way: for a shared borrow, the place may not be mutated, but it may be read or shared again; for a mutable borrow, the place may not be accessed in any way until the borrow expires. The error index entry for E0502 states the same rule from the failure side: a variable already borrowed with one mutability was borrowed again with a different mutability.

The reason for the rule is aliasing. A shared reference is a promise that the value behind it will not change while the reference is in use; code holding one may rely on the value staying put, and the compiler may rely on it too. A mutable reference is the opposite promise: exclusive access, so the holder may change the value without invalidating anyone else's view, because no one else has a view. Allowing both at once would break both promises in a single step. The classic concrete harm is invalidation: growing a Vec can move its storage, so a reference to an element held across a push could be left pointing at freed memory. The rule rejects the program before that can happen, at compile time, with the three relevant source positions named.

The second half of the rule decides most real cases, and it is about time, not text. A borrow is alive from where it is created until its last use — not until the end of the block, not until the variable goes out of scope. The Rustonomicon puts it directly: a reference is alive from the place it is created to its last use, and the borrowed value needs to outlive only borrows that are alive. The Book says the same in scope language: a reference's scope starts where it is introduced and continues through the last time that reference is used. This is the behavior often called non-lexical lifetimes. It means the textual order of declarations matters far less than the order of uses. A borrow declared early but used for the last time before a mutation is already dead at the mutation, and the mutation is allowed. A borrow declared early and used even once after the mutation is alive across it, and the mutation is refused. When you read E0502, read the diagnostic's third note first — the one marking where the first borrow is later used — because that use, not the borrow's birth, is what you have to move, finish, or eliminate.

One more mechanism belongs in the rule, because it decides a common method-call case below. In a method call, the receiver borrow and the argument evaluation are allowed a limited overlap called a two-phase borrow: the receiver is first reserved, the arguments are evaluated, and only then is the receiver borrow fully activated. That is why a call can read the receiver inside its own argument list. The permission is narrow — it covers that one call's argument evaluation, not a reference stored in a variable beforehand — and the section on method calls below shows both sides of the line with programs.

The first failure: a shared borrow held in a variable, then a mutation

The smallest program that produces the title error keeps a reference to the first element of a vector, mutates the vector, and only then prints the reference:

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

error: aborting due to 1 previous error

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

Read the diagnostic in its three positions, because together they are a complete account of the overlap. The first note marks where the shared borrow occurs: the indexing expression &v[0], which borrows v immutably to read its first element. The headline and the caret span mark where the mutable borrow occurs: v.push(4), because push takes &mut self and therefore needs exclusive access to v. The third note marks where the immutable borrow is later used: the println! that reads first. That third position is the load-bearing one. It proves the shared borrow must stay alive across the push — the program itself asks to read through it afterward — so the overlap is real, and no reordering of declarations can remove it. Either the later use moves before the mutation, or the value it needs is extracted before the mutation, or the program's shape changes. Those are the first and third fixes below.

Note also what the error is not claiming. It is not claiming that push is dangerous in itself, or that indexing is suspect, or that the two statements are too close together. Move the println! that uses first to any position after the push, in any later statement, through any amount of intervening code, and the same error returns with the later-use note pointing at the new position. Remove that later use entirely and the error disappears — which is exactly the next section.

The case that now compiles: the borrow whose last use comes first

Change nothing except the order of the two println! calls' work — print first before pushing, and never use first again — and the program the previous section failed compiles and runs:

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

This is the most common confusion around E0502, and it is worth stating plainly: code that older explanations show as failing — a borrow, a mutation, and the end of a scope, in that order — is accepted by the current compiler when the borrow's last use precedes the mutation. The variable first still exists, as a name, after the push. It is in scope. Nothing about its declaration changed. What changed is that nothing reads it after the push, so its borrow ended at the println! above the push, and at the moment push requests exclusive access there is no live borrow to conflict with it.

Two practical consequences follow. The first is that advice phrased in terms of scopes — wrap the borrow in braces so it ends sooner — is a blunt version of a precise rule. Braces work when they also move the last use inside them; they do nothing when a use remains outside. Work in terms of last use instead: find the final read of the borrowed value, and ask whether the mutation can go after it, or whether that read can go before the mutation, without changing what the program computes. The second consequence is diagnostic: when E0502 surprises you in code that looks like this section — borrow high in the function, mutation lower — do not look at the borrow. Look for the stray later use. A debug print left below the mutation, a log line, an assertion at the end of the function: any one of them extends the borrow across the mutation and produces the full error for the sake of a read the program may not even need there.

There is a boundary case worth knowing, stated here without a program of its own because it follows from the same last-use rule: a value whose type runs a destructor counts that destructor as a use at the end of the scope, so a borrow held by such a value can stay alive longer than its visible reads suggest. The Rustonomicon's lifetimes chapter works that case in full; the Sources list points to it. Ordinary references to plain data, as in every program in this guide, carry no destructor and end at their last ordinary use.

The second failure: iterating a collection while mutating it

The loop form of E0502 is the one working code meets most often. The intent is natural — walk a vector and append a derived value for each element — and the borrow structure forbids it directly, because the loop itself is the long-lived reader:

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    for x in &v {
        v.push(x * 10);
    }
    println!("v = {v:?}");
}
Terminal
$ rustc --edition 2021 fail_iter.rs -o fail_iter
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> fail_iter.rs:4:9
  |
3 |       for x in &v {
  |       -        --
  |       |        |
  |       |        immutable borrow occurs here
  |  _____|        immutable borrow later used here
  | |
4 | |         v.push(x * 10);
  | |         ^^^^^^^^^^^^^^ mutable borrow occurs here
5 | |     }
  | |_____- this for loop borrows `v` immutably, preventing mutation within its body
  |
  = help: consider using an index-based loop instead, or collecting modifications into a separate collection

error: aborting due to 1 previous error

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

The diagnostic differs from the canonical form in one instructive way: the later-use note does not point at a single later statement, because the later use is the loop itself. Iterating over &v borrows v immutably for the whole traversal — each element reference x derives from that borrow, and the iterator must keep the collection stable and unchanged to hand out the next element soundly. The closing note says it in one line: this for loop borrows v immutably, preventing mutation within its body. Unlike the canonical form, there is no stray use to move and no reordering inside the body that helps, because the borrow and the mutation are interleaved by construction — read an element, mutate, read the next element, mutate. The fix must change the traversal's shape: walk by index, collecting the length first, so no borrow spans an iteration; or collect the new values separately and append them after the loop; or, where the mutation is to elements already present rather than to the collection's length, iterate mutably with iter_mut and never touch the collection itself. The index form is the second fix below, and the compiler's own help line names it first.

A related expectation deserves a direct answer, because it fails for a subtler reason than readers expect: pushing does not become allowed if the vector has spare capacity and no reallocation would occur. The borrow checker does not reason about capacity. push needs &mut v by its signature, a live shared borrow of v forbids that by the rule, and the analysis stops there. Capacity is a runtime fact the checker does not track, in this program or any other.

The method-call form: one call that compiles, and one that does not

Method calls produce the two most misleading encounters with this error, because two programs that look alike fall on opposite sides of it. The first compiles:

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

push needs &mut v. Its argument, v.len(), needs &v. Read naively, that is the forbidden mix inside a single statement, and code in this shape was indeed rejected by early versions of the language. It is accepted now under two-phase borrows: the mutable borrow of the receiver is reserved, the argument is evaluated under a limited shared access, and the mutable borrow is activated only for the call itself. The argument's read is finished before the mutation begins, so no live shared borrow survives into the write. The same permission is what allows the familiar v.push(v[0]) shape and in-place updates written as a single call.

The permission ends exactly at that call's argument list. Hold the read in a variable first — which is what any nontrivial computation naturally does — and the identical operations fail, because now a named shared borrow is alive across the call rather than a transient argument read inside it:

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

error: aborting due to 1 previous error

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

sort takes &mut self, so it stands in the same position as push in the canonical failure, and r is used after it, so the borrow is alive across it. The lesson to carry is precise: two-phase borrows rescue a read written inside the argument list of the mutating call itself. They do not rescue a borrow taken on an earlier line, however short-lived it feels, and they do not extend to a second statement. If a computation is too large for an argument expression, compute it into an owned value before the call — which is the first fix — rather than holding it as a reference and expecting the call to be forgiven.

Fix 1: end the first borrow — compute the value, then mutate

Reach for this fix first, because most E0502 programs need a value from the borrowed data, not the borrow itself. If everything the later code needs from the shared borrow can be extracted into an owned value before the mutation — a copied number, a computed length, a decision already made — then extract it, let the borrow end, and mutate freely. The canonical failure needs only the first element's value after the push, and an i32 is copied by a single dereference:

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

The block makes the borrow's lifetime visible: borrowed exists only inside the braces, its value is copied out as the block's result, and by the time push runs there is no reference to v anywhere in the program. In many real programs the block is not even needed — writing let first = v[0]; copies the element directly, and the temporary borrow inside that one statement ends with the statement. The block form is shown because it generalizes to the case where the extraction takes several steps: read fields, compute, combine — all inside the block, with only the owned result crossing its boundary. Judge this fix by what crosses that boundary. Owned values cross freely. A reference crossing the boundary carries the borrow with it and reproduces the original error one line lower.

The reorder variant of this fix is even smaller when it applies: if the later use is a pure read with no dependence on the mutation — a print, a log, a check of the pre-mutation state — move it above the mutation, as the compiles-now section showed. Reordering is correct only when the read genuinely wants the value as it was before the mutation. A read moved carelessly across a mutation it was meant to observe is a silent behavior change wearing a borrow fix as a costume, so state, in the commit or the review, which value the read was intended to see.

Fix 2: split the work by index, so no borrow spans a mutation

For the loop failure, replace the borrowed traversal with positions. Capture the length once, walk indices, and read each element by a fresh, short-lived borrow inside the iteration — each read ends before that iteration's push begins:

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    let n = v.len();
    for i in 0..n {
        let x = v[i];
        v.push(x * 10);
    }
    println!("v = {v:?}");
}
Terminal
$ rustc --edition 2021 fix_index.rs -o fix_index
$ ./fix_index
v = [1, 2, 3, 10, 20, 30]

Two details make this version correct rather than merely compiling. The length is captured before the loop, so the loop visits exactly the original elements and does not chase its own appends; a condition written as i < v.len() inside the loop would re-read the growing length and never terminate on this logic. And each v[i] read copies the element into x and ends immediately, so at the push no borrow is alive — the same last-use principle as Fix 1, applied once per iteration. Where the elements are not cheap to copy, collect instead: iterate the shared borrow read-only, build the new values in a separate vector, and append that vector after the loop with append or extend. The collection form keeps the natural traversal, costs one temporary buffer, and is the compiler help line's second suggestion for this error.

Fix 3: split the data, so both borrows are allowed at once

Sometimes the read and the write genuinely must proceed together, but they touch different elements. Then the correct move is to split the collection into disjoint parts and borrow each part separately, in a form the compiler can prove disjoint. split_at_mut is the standard tool: it takes one mutable borrow of a slice and returns two mutable borrows of its non-overlapping halves, after which either half can also be read while the other is written:

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

The read of left[0] and the write to right[0] overlap in time completely, and the program compiles, because left and right borrow disjoint ranges and the checker knows it — the split is the proof. The same family covers split_at, chunks_mut, chunks_exact_mut, and the two-index case handled by comparing positions before borrowing, but the discipline is constant: the disjointness must come from an operation whose contract states it, not from the programmer's private knowledge that two indices differ. Two ordinary index expressions into the same vector, v[i] held while v[j] is mutated, still borrow the whole of v each time and still fail, however obvious it is to a reader that i and j differ. Reach for this fix when the algorithm is genuinely element-against-element — comparing halves, swapping regions, updating one part from another — and for the disjoint-parts pattern inside structs, where borrowing two distinct fields at once is allowed for the same reason and holding a method's &mut self across both is what usually breaks it.

Fix 4: restructure — return a value instead of holding a reference

When the borrow is held across a mutation because a helper returns a reference, or because the code is organized as borrow-then-act, restructure the boundary: have the helper return an owned value, and let the caller's mutation work on data no reference points into. The canonical shape, with the reading logic in a function, becomes:

Rust
fn first_or_zero(v: &[i32]) -> i32 {
    v.first().copied().unwrap_or(0)
}
fn main() {
    let mut v = vec![1, 2, 3];
    let first = first_or_zero(&v);
    v.push(first * 10);
    println!("first = {first}");
    println!("v = {v:?}");
}
Terminal
$ rustc --edition 2021 fix_restructure.rs -o fix_restructure
$ ./fix_restructure
first = 1
v = [1, 2, 3, 10]

The helper's borrow begins and ends inside the call. What crosses the function boundary is an i32, owned by the caller, and the subsequent push has nothing to conflict with. This is Fix 1 viewed from the design side — the same extraction, but placed at an API boundary so every caller benefits — and it is the fix that scales: a function that returns a reference into its argument forces every caller to schedule mutations around that reference, while a function that returns a value leaves callers free. It is also the direction the Rustonomicon's own worked example takes, replacing a function that tries to return a reference to a local value with one that returns the owned value itself. Restructure when the held reference crosses a statement boundary repeatedly, when several mutations are scheduled around one borrow, or when the borrow's lifetime has started dictating the shape of unrelated code. The cost is the copy or computation the return performs, paid once, in one visible place.

A smaller restructure in the same family deserves mention because it resolves a neighboring confusion: a mutable borrow can be used again and again through reborrowing, where each call takes a fresh borrow derived from the held one and returns it. Passing a &mut variable to two calls in sequence, then using the variable itself, is accepted — each call's reborrow ends when the call returns. Code that fails with a moved or consumed mutable reference often needs an explicit reborrow, written &mut *r, rather than any change to its borrow structure. That behavior concerns mutable borrows competing with each other, the territory of error E0499 rather than E0502, but it is probed alongside this guide's programs and stated here so the two errors are not conflated.

Fix 5: clone, as the deliberate last resort

Cloning ends any borrow conflict by severing the connection: copy the data out from under the shared borrow, drop the borrow, and mutate the original while working with the copy. For data that is not Copy, the copy is explicit:

Rust
fn main() {
    let mut v = vec![String::from("a"), String::from("b")];
    let first = v[0].clone();
    v.push(first.clone());
    println!("first = {first}");
    println!("v = {v:?}");
}
Terminal
$ rustc --edition 2021 fix_clone.rs -o fix_clone
$ ./fix_clone
first = a
v = ["a", "b", "a"]

The program is correct, and its costs are printed in its own text: two clones for one append, each allocating a new String and copying its bytes. That is the honest price of this fix, and it grows with the data — cloning a string copies its heap buffer, cloning a vector copies every element, cloning inside a loop pays on every iteration. Clone when the copy is small, cold, or genuinely wanted as an independent value the program will keep and mutate separately; a snapshot taken before a transformation is a legitimate clone, not a borrow workaround. Clone reluctantly when the copy exists only to satisfy the checker on a hot path, because in that position it is usually evidence that Fix 1 or Fix 4 was available — the program needed a value, and extracting it directly is the same copy without the pretense of still sharing the original. The decision is economic, not moral: state what is copied, how often, and why no extraction or split applied, and the clone is a defensible engineering choice rather than a reflex.

The trap: silencing the checker instead of ending the overlap

Trap
Two moves make E0502 disappear without fixing anything, and both convert a compile-time guarantee into a runtime hope. Name them so they can be refused on sight.

The first is sprinkling .clone() at every error site until the program compiles. Section by section it looks like Fix 5; as a habit it is different in kind, because no one decided what the copies cost or whether the program now works on stale data. The sharpest failure is semantic, not financial: code that clones an element, mutates the collection, and then writes the clone back can silently discard changes made in between, and code that reads the clone after the mutation reads the pre-mutation value while appearing to read the current one. The compiler error was pointing at a real question — should this code see the value before or after the change — and the blanket clone answers it by accident, differently at each site.

The second is wrapping the value in Rc<RefCell<T>>, or Arc<Mutex<T>> in threaded code, so that borrowing is checked dynamically instead of statically. RefCell enforces the same rule — many readers or one writer — but at runtime: borrow_mut panics if the value is currently borrowed, as its documentation states for both borrow methods. Nothing about the overlap is resolved; the program that the compiler refused now compiles, runs, and panics at the exact moment the overlap occurs, in production, on whichever input first exercises that path. Interior mutability has legitimate designs behind it — graph structures, caches, observer patterns where the borrow structure is genuinely dynamic — and in those designs the runtime check is the honest mechanism, chosen for the structure. Adopted as an E0502 silencer for ordinary sequential code, it trades a free, exhaustive, compile-time proof for a partial runtime check and a new panic mode, and it spreads: once a value is behind a RefCell, every access in the program pays the ceremony, and the type signature stops telling readers who may change the value and when. If a design truly needs it, that need can be stated in terms of the data structure, not in terms of an error message.

Which fix for which error

What the diagnostic shows What is actually happening First fix to reach for
Borrow in a variable, later use after the mutation The later use keeps the shared borrow alive across the write Fix 1 — move the use before the mutation, or extract an owned value first
No visible later use, error still fires A stray read below the mutation — a print, log, or assertion — or a destructor counting as a last use Find the last use, then Fix 1
For loop over &collection, mutation in the body The traversal holds the shared borrow for the whole loop Fix 2 — index loop with the length captured first, or collect then append
Read inside the mutating call's own arguments fails The read is not a plain argument expression, or a named borrow from an earlier line is involved Inline the read as the argument, or Fix 1 — two-phase borrows cover only the argument list
Read and write must overlap, on different elements One borrow of the whole collection is being used for disjoint parts Fix 3 — split_at_mut, chunks_mut, or a field-level split
A helper returns a reference the caller must hold across mutations The API boundary exports a borrow and imports the conflict into every caller Fix 4 — return an owned value
The copied value is small, cold, or wanted independently Sharing was never essential; an owned snapshot is the real design Fix 5 — clone, with the cost stated

Checklist

  • Read all three positions in the diagnostic before editing: where the shared borrow occurs, where the mutable borrow occurs, and where the shared borrow is later used. The third position selects the fix.
  • Work in last uses, not scopes: a borrow ends at its final read, and any print, log, or assertion after the mutation counts as a read that extends it.
  • Extract before you clone: if an owned value — a copy of a Copy element, a length, an index, a computed result — carries everything the later code needs, extract it and let the borrow end.
  • In loops, capture the length before an index traversal that appends, and never let a loop condition consult a length the body is growing.
  • Split only through operations whose contract proves disjointness: split_at_mut and its relatives, or distinct fields. Two indices the programmer knows differ are not a split the checker can see.
  • Keep two-phase borrows in their place: a read inside the mutating call's argument list is allowed; a borrow named on an earlier line is a different program and fails on its own merits.
  • Return values across function boundaries where callers must mutate afterward; return references only when the caller's borrow-then-read pattern is the actual design.
  • Treat every .clone() added under error pressure as a decision to record: what was copied, how large it can grow, how often it runs, and why extraction or a split did not apply.
  • Treat RefCell adopted to silence this error as a rejected fix: the same rule returns as a runtime panic. Adopt interior mutability for data-structure reasons or not at all.
  • After the fix, read the changed code again for the semantic question the error was asking: does each read see the value before the mutation or after it, and is that the value the program intends?
  • Rust Ownership and Borrowing — the concepts guide behind this error: moves, borrows, and clones as a system, where this guide is the single-error repair manual for the moment that system refuses a program.
  • Rust Structs and Enums — the data definitions the borrows point into, including the field-level access that makes disjoint field borrows, and the splits in Fix 3, possible.

Sources

  • Rust Project, Error codes index: E0502 — for the definition of E0502 as a variable borrowed with one mutability being borrowed again with a different mutability, and for the index's own fix shape, removing the conflicting borrow before the second access.
  • Rust Project, The Rust Reference: Operator expressions — for the borrow operators' semantics: a shared borrow places the value in a state where it may not be mutated but may be read or shared again, and a mutable borrow excludes any other access until the borrow expires.
  • Rust Project, The Rust Programming Language: References and Borrowing — for the rule against holding a mutable reference alongside immutable ones, for the data-race rationale, and for a reference's scope running from its introduction through its last use, with the worked example of immutable borrows ending before a mutable borrow begins.
  • Rust Project, The Rustonomicon: Lifetimes — for a reference being alive from its creation to its last use, for the worked desugaring of this guide's canonical vector program, for the destructor counting as a final use, and for returning an owned value in place of a reference that cannot be produced.
  • Rust Project, std::primitive slice — for the slice method family behind Fix 3, including split_at_mut and the chunk splitters, which divide one borrow into provably disjoint parts.
  • Rust Project, std::cell::RefCell — for borrow panicking when the value is currently mutably borrowed and borrow_mut panicking when the value is currently borrowed, the runtime form of the same rule cited in the trap section.

Keep Exploring