References let you borrow a value. Immutable references &T allow many readers; mutable &mut T allows one writer at a time.
Rules
- Any number of
&TOR exactly one&mut Tin a scope - References must not outlive the data they point to
Example
fn len(s: &String) -> usize { s.len() }
Important interview questions and answers
- Q: Why one mutable borrow?
A: Prevents data races and aliased mutation at compile time.
Self-check
- Can you have two
&mutto the same data? - What sigil marks a reference?
Pitfall: You cannot hold a mutable reference while any shared references exist in the same scope—split scopes or clone data.
Interview prep
- Why only one mutable borrow?
Prevents aliased mutation and data races—the compiler rejects conflicting borrows at compile time.