How to fix Rust E0499 cannot borrow as mutable more than once

Fix Rust E0499 by ensuring immutable borrows end before mutable borrows begin, or use RefCell for interior mutability.

Error E0499 occurs because you are trying to borrow a value mutably while an immutable borrow is still active. You must ensure the immutable borrow ends before starting the mutable one, typically by restructuring the code to avoid overlapping scopes.

fn main() {
    let mut s = String::from("hello");
    
    // Immutable borrow starts here
    let r1 = &s;
    
    // Immutable borrow ends here (scope of r1)
    
    // Mutable borrow starts here (safe because r1 is gone)
    let r2 = &mut s;
    
    println!("{}", r2);
}

If you need both borrows simultaneously, use interior mutability with RefCell instead:

use std::cell::RefCell;

fn main() {
    let s = RefCell::new(String::from("hello"));
    
    let r1 = s.borrow(); // Immutable borrow
    let r2 = s.borrow_mut(); // Mutable borrow (panics at runtime if r1 is active)
    
    // Use r1 and r2 carefully
}