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);
}
The "cannot borrow as mutable because it is also borrowed as immutable" error happens because Rust prevents you from reading and writing to the same piece of data at the exact same moment to avoid crashes. Think of it like a library book: you cannot check it out to read (immutable) while someone else is trying to write notes in it (mutable). You must finish reading and return the book before anyone can start writing in it.