How does the borrow checker work internally

The borrow checker is a compile-time mechanism that enforces Rust's ownership rules to prevent data races and memory safety issues by validating reference lifetimes and mutability.

The borrow checker is a compile-time analysis that enforces Rust's ownership rules to ensure memory safety without a garbage collector. It verifies that references are valid by ensuring there is only one mutable reference or any number of immutable references to a value at any given time, and that references do not outlive the data they point to. You can see this in action when the compiler rejects code that attempts to mutate a value while an immutable reference exists, or when a reference dangles after its owner is dropped.

let mut s = String::from("hello");
let r1 = &s; // Immutable borrow
let r2 = &s; // Immutable borrow
// let r3 = &mut s; // ERROR: Cannot borrow `s` as mutable because it is also borrowed as immutable
println!("{} and {}", r1, r2);
// r1 and r2 are no longer used here
let r3 = &mut s; // OK: Mutable borrow is now allowed
r3.push_str(", world");