You cannot borrow a value as mutable while an immutable borrow is still active because Rust prevents data races by enforcing exclusive access for mutation. To fix this, ensure the immutable borrow ends before the mutable borrow begins, typically by moving the read operation outside the scope of the write or restructuring the logic to avoid overlapping lifetimes.
let mut data = vec![1, 2, 3];
// Immutable borrow ends here
let first = data[0];
// Mutable borrow starts here, after immutable borrow is gone
data[0] = 10;
println!("First: {}, Updated: {:?}", first, data);
Alternatively, if you need to read and write to different parts of a collection, use indexing or slicing to create non-overlapping borrows:
let mut data = vec![1, 2, 3];
// Borrow first element immutably
let first = data[0];
// Borrow the rest mutably (non-overlapping)
for item in &mut data[1..] {
*item *= 2;
}
println!("First: {}, Rest: {:?}", first, data);