Rust Borrowing and References
🦀 Rust Borrowing and References
This is what makes Rust safe, fast, and free from data races.
Think of it like this:
-
Ownership = you own the house
-
Borrowing = someone visits the house (can see or modify based on permission)
🧠 What Is a Reference?
A reference is like a pointer that:
-
Points to a value
-
Does not own it
-
Is guaranteed to be safe (no dangling pointers)
Syntax:
🔹 1. Immutable Borrowing (&)
You can borrow a value read-only.
✔ Ownership stays with name
✔ Function only reads data
✔ Multiple immutable borrows allowed
🔹 2. Mutable Borrowing (&mut)
You can borrow a value with permission to modify it.
✔ Value must be declared mut
✔ Only one mutable borrow at a time
🔑 Borrowing Rules (VERY IMPORTANT)
Rule 1: Multiple immutable borrows allowed
Rule 2: Only one mutable borrow at a time
Rule 3: Cannot mix mutable and immutable borrows
👉 This prevents data races.
🔹 3. Borrowing and Scope
Borrowing follows scope rules.
🔹 4. References Prevent Dangling Pointers
Rust will not compile code that creates dangling references.
✔ Rust catches this at compile time
Correct way:
🔹 5. Borrowing with Slices (&str)
Slices are references.
✔ Very efficient
✔ No ownership transfer
🔹 6. Borrowing in Functions (Best Practice)
Prefer references in function parameters.
✔ Works with String and &str
✔ No ownership issues
✔ Flexible & efficient
❌ Common Borrowing Mistakes
-
Multiple mutable references at once
-
Mixing
&and&mut -
Returning references to local variables
-
Forgetting scope ends borrowing
🧠 Borrowing Summary
| Concept | Meaning |
|---|---|
&T |
Immutable reference |
&mut T |
Mutable reference |
Multiple & |
Allowed |
Multiple &mut |
❌ Not allowed |
& + &mut |
❌ Not allowed |
