Course contentsShow
← Rust
Lesson 228 of 1,9103. Borrowing and ReferencesFree lesson

Handling Borrow Errors

Interpret compiler error messages related to conflicting borrows.

In this lesson, you will learn how to read and resolve the most common "conflicting borrow" errors generated by the Rust compiler.

When the borrow checker stops your code, it is essentially acting as a strict librarian ensuring that no one is modifying a book while others are reading it. The compiler messages might seem intimidating, but they follow a predictable pattern. They usually point out two things: where the first borrow happened and where the conflicting borrow occurred.

Consider this common mistake:

fn main() {
    let mut data = vec![1, 2, 3];
    let reader = &data;          // First borrow (Immutable)
    data.push(4);               // Error: Mutable borrow happens here!
    println!("{:?}", reader);
}

Understanding the Error

When you run this, the compiler says: cannot borrow 'data' as mutable because it is also borrowed as immutable.

  1. Locate the first borrow: The compiler will highlight let reader = &data. This creates a shared reference that remains active until its last use.
  2. Locate the conflict: It points to data.push(4). Because push requires exclusive access, it cannot proceed while reader is alive.
  3. Trace the Scope: The "lifetime" of reader lasts until the println! call. Even though you aren't using reader on the line where you call push, the borrow checker sees that the reference is still "in scope."

How to Fix It

To resolve these errors, you have three primary strategies:

  • Shorten the scope: Wrap the conflicting borrow in a new block { ... } so the reference goes out of scope before the mutation occurs.
  • Clone the data: If you absolutely need to read and write at the same time, you may need to clone the value so you have two independent copies (though be mindful of memory usage).
  • Rearrange the order: Ensure that all mutable operations are finished before you create your immutable references, or finish using your references before you attempt a mutation.

By identifying the "active" life of your references, you can clear these errors by simply ensuring the two types of access never overlap in time.

Key Takeaway: When the compiler reports a borrow error, identify the scope of the existing reference and ensure it is no longer being used before you attempt to perform a mutable operation.