Mutable references give temporary write permission while the original owner retains ultimate ownership.
The Borrowing Rules
Rust enforces strict borrowing rules at compile time to prevent data races:
Rule 1: Multiple Immutable References
You can have multiple read-only references:
fnmain() {
lets = String::from(\"hello\");
let r1 = &s; // First reference
let r2 = &s; // Second reference
let r3 = &s; // Third reference
println!(\"r1: {}, r2: {}, r3: {}\", r1, r2, r3); // All OK
}
Rule 2: Only One Mutable Reference
At any time, you can have ONE mutable reference OR multiple immutable references, but not both:
fnmain() {
letmut s = String::from(\"hello\");
let r1 = &s; // Immutable reference
let r2 = &s; // Another immutable
// let m = &mut s; // ERROR! Can't have mutable while immutable refs exist
println!(\"r1: {}, r2: {}\", r1, r2);
}
Why This Rule?
This prevents data races. Consider this scenario in other languages:
// Hypothetically without borrowing rulesletmut data = 10;
letref1 = &data; // Reference// ... if another thread modifies data ...
data = 20;
println!(\"ref1: {}\", ref1); // Undefined behavior!
Rust's rules prevent this at compile time.
Reference Scope
References go out of scope when they're last used, not when declared:
fnmain() {
letmut s = String::from(\"hello\");
let r1 = &s;
let r2 = &s;
println!(\"r1: {}, r2: {}\", r1, r2); // Last use of r1 and r2
// r1 and r2 are out of scope here
let m = &mut s; // OK! No immutable refs in scope
println!(\"m: {}\", m);
}