Skip to content
Latchkey

Rust "error[E0502]: cannot borrow as mutable" in CI

The borrow checker found an active immutable borrow overlapping a mutable one. Rust allows many shared borrows or one exclusive borrow, never both at once -- so the conflicting borrows must be separated.

What this error means

cargo build fails with error[E0502]: cannot borrow x as mutable because it is also borrowed as immutable (or the E0499 two-mutable-borrows variant), pointing at the overlapping borrows. The build stops.

cargo
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let first = &v[0];
  |                  - immutable borrow occurs here
4 |     v.push(1);
  |     ^^^^^^^^^ mutable borrow occurs here
5 |     println!("{first}");
  |               ------- immutable borrow later used here

Common causes

Immutable and mutable borrows overlap

A reference into a collection (or a field) is still live when you also take a mutable borrow -- e.g. holding &v[0] across a v.push(...).

Two mutable borrows at once (E0499)

Two &mut references to the same value coexist, which the borrow checker forbids.

How to fix it

Scope the borrows so they do not overlap

Finish using the first borrow before taking the conflicting one.

Rust
let first = v[0];      // copy/clone the value, ending the borrow
v.push(1);             // now the mutable borrow is fine
println!("{first}");

Split borrows or restructure

  1. Move the mutable operation after the immutable borrow is no longer used.
  2. Copy or clone small values instead of holding a reference across a mutation.
  3. Use indices, split_at_mut, or scopes to avoid overlapping &/&mut.

How to prevent it

  • Keep borrows short and non-overlapping; end one before starting a conflicting one.
  • Run cargo check locally to catch borrow conflicts before CI.
  • Reach for indices or split_at_mut when you need disjoint mutable access.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →