Borrowing in Rust is a mechanism for temporarily "borrowing" a variable through references. Rust distinguishes between immutable borrowing (&T) and mutable borrowing (&mut T). There can be as many immutable references as you want at the same time, but only one mutable reference. It is not allowed to have mutable and immutable references to the same object at the same time.
This rule ensures the absence of data races at compile time and makes Rust safe for concurrent programming.
Example:
let mut value = 5; let r1 = &value; let r2 = &value; // let r3 = &mut value; // ERROR: cannot create &mut while there are & references println!("{} {}", r1, r2); // r3 is prohibited until the end of the scope of r1/r2
Question: Can you create one &mut reference and as many & references to the same object in the same scope?
Typical incorrect answer: Yes, but only if they do not overlap in lifetime.
Correct answer: A mutable and an immutable reference to the same object cannot exist at the same time (even if accesses do not overlap statically in code); while one is alive, the others are prohibited. Safety is checked by the borrow checker.
Example:
let mut x = 10; let y = &x; let z = &mut x; // Error, y is still in scope println!("{}", y); // y is needed later
Story
In a large project with parallel data processing, a developer decided to use immutable references to a vector and then tried to obtain a mutable reference for sorting. The code worked in tests but stopped compiling after refactoring because the lifetime of the immutable references was extended.
Story
In an internal service, the structure was modified through
&mut, while keeping references to the fields for later sending to another thread. A data race occurred and a crash happened due to violating borrow rules—Rust protects against this only at compile time, but errors occurred in unsafe blocks where guarantees are removed.
Story
Incorrect API documentation: a library accepted both
&and&mutfor different fields of a structure, but due to aliasing, invariants were violated, leading to elusive bugs with services integrating this library.