Error

"cannot borrow as mutable because it is also borrowed as immutable" — How to Fix

Fix the Rust borrow checker error by ensuring immutable and mutable references to the same data do not overlap in scope.

You cannot have both a mutable reference (&mut T) and an immutable reference (&T) to the same data active at the same time. Separate the scopes of your references so the immutable borrow ends before the mutable one begins.

let mut data = vec![1, 2, 3];

// Immutable borrow scope
{
    let immutable_ref = &data;
    println!("Read: {immutable_ref}");
}
// immutable_ref is dropped here

// Mutable borrow scope
{
    let mutable_ref = &mut data;
    mutable_ref.push(4);
}