Topic
Borrowing
Borrowing lets you use a value without taking ownership. You pass a reference instead of the value itself, and the original stays valid. The borrow checker enforces two rules: only one mutable reference at a time, and references must always point to valid data.
Quick Reference
| Concept | What it means |
|---|---|
| &T | An immutable reference — borrow a value for reading only |
| &mut T | A mutable reference — borrow a value and be allowed to change it |
| Rule 1 | Either one mutable reference or any number of immutable ones, never both at the same time |
| Rule 2 | References must always be valid — no dangling pointers |
| Dangling reference | A reference to data that has already been dropped. Rust refuses to compile this. |
| Inner scope { } | Wrapping a reference in a block drops it when the block ends, freeing the borrow |
| Term | What it means | When you use it |
|---|---|---|
| Borrow &T | A read-only reference — you can look but not change | When a function only needs to read a value |
| Mutable borrow &mut T | A read-write reference — you can change the value | When a function needs to modify a value |
| Rule 1 | Either one mutable reference or any number of immutable ones, never both | Every time you create a reference |
| Rule 2 | References must always be valid — no dangling pointers | Compiler enforces this automatically |
| Lifetime | How long a reference stays valid — compiler tracks this automatically | You read lifetimes in Anchor; rarely write them yourself |
| Inner scope | Wrapping a reference in { } drops it when the block ends | When you need sequential mutable references |