Code Example Template
Deep-Dive System Documentation
Borrowing: References
Instead of transferring ownership every time you want to inspect a value, you can borrow it. Borrowing creates references (pointers to the original data).
The Borrowing Rules
Rust strictly enforces these two compile-time constraints:
- You may have any number of shared references (
&T) to a resource. - OR you may have exactly one exclusive mutable reference (
&mut T) to a resource. - You cannot have both at the same time.
let mut active_profile = String::from("Default");
let ref1 = &active_profile; // OK: Shared borrow
let ref2 = &active_profile; // OK: Multiple shared borrows are allowed
// let mut_ref = &mut active_profile; // ERROR: Cannot borrow as mutable while shared borrows exist!
Why?
Enforcing these rules prevents data races. A data race occurs when two references access the exact same memory address concurrently, at least one is writing, and there is no thread synchronization. By blocking concurrent read-write access, Rust eliminates crashes in multi-threaded input listeners before they can compile.
Quick Reference Guide
let x = 5;
let r = &x; // read-only reference