Rust E0502: Cannot borrow as immutable while mutable borrow active
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/main.rs:10:15
= help: use `iter` to access elements without re-borrowing
Immediate Remediation
bash
cat > src/main.rs <<'EOF'
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0]; // copy before mutation
for item in v.iter_mut() {
*item += first;
}
}
EOFRoot Cause Analysis
The borrow checker rejected the code because an immutable borrow of `v` was attempted while a mutable borrow (from `iter_mut()`) was still active, violating Rust's ownership and borrowing rules.
Verification & Guardrails
- This fix assumes the element type implements Copy; if not, use `v.first().cloned()` or restructure to avoid borrowing the whole vec.
- If you need to read and mutate the same collection during iteration, consider using `RefCell` or `Cell` for interior mutability.
- Verify the fix with `cargo check` and ensure no other borrows conflict in the surrounding scope.
Have a custom or uncategorized crash?
Run your trace through our in-memory client privacy sandbox for instant SRE remediation.