How to fix Rust E0502 cannot borrow as mutable

Fix Rust E0502 by ensuring immutable borrows end before starting mutable borrows to prevent overlapping access.

The E0502 error occurs because you are trying to borrow a value mutably while an immutable borrow of the same value is still active. You must ensure the immutable borrow ends before starting the mutable one, often by restructuring the code or using indices instead of references.

let mut s = String::from("hello");
let r1 = &s; // Immutable borrow starts
// let r2 = &mut s; // ERROR: E0502 - cannot borrow as mutable

// Correct approach: ensure r1 is no longer used
let r1 = &s;
println!("r1: {}", r1); // r1 used here
// r1 scope ends implicitly if not used further, or explicitly via block
{
    let r2 = &mut s; // Mutable borrow starts after r1 is done
    r2.push_str(" world");
}