liveBook · Manning

Borrow checker

As explained in Code Like a Pro in Rust

A borrow checker is a compiler component that enforces rules governing references and ownership to prevent invalid memory access.

The borrow checker is part of Rust’s compiler, rustc. It validates references at compile time to enforce Rust’s memory-management rules, rather than relying on runtime reference counting or garbage collection. section 1.1 section 1.2.1

For a variable or object, the rules are:

  • Multiple immutable references are allowed. section 1.2.1
  • Only one mutable reference may be active at a time; it cannot overlap with an immutable reference. section 1.2.1
  • A reference cannot outlive the variable it refers to. section 1.2.1

Conflicting borrows

`let mut value = String::from("data"); let read = &value; let write = &mut value; println!("{read} {write}");` The mutable and immutable references are both used, so rustc rejects their overlap. Arrange access so conflicting borrows are not active together. section 1.2.1

Treat these compiler checks as a boundary for testing, not a replacement for it. Tests should focus on program logic, failed conversions, stateful operations, and I/O; handle fallible paths explicitly rather than using `unwrap()` or `unsafe` to bypass edge cases. section 6.4

How Code Like a Pro in Rust covers it

How deep it goes
Defines mutable and immutable borrowing limits and scope validity, without detailing compiler algorithms.
Examples
Illustrates conflicting references with a borrowing-rules diagram and contrasts compiler checks with logic tests.
What it assumes
Introduces the borrow checker without requiring prior familiarity with it, using references and mutability to state its rules.
What you can do after
Apply it via rustc to reject invalid references, then test logic and fallible operations separately.
How it connects
Connects borrowing to RAII, memory safety, concurrent programming, and unit testing.

Also explained in

Compare how 4 books explain borrow checker →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.