TL;DR
- Every value has one owner. When the owner goes out of scope, value is dropped.
- Move = transfer ownership. Old variable is invalidated.
- Borrow = reference without ownership.
&T (read), &mut T (write).
- Rules: One
&mut OR many & at a time. Never both.
Quick Reference
// Move
let s1 = String::from("hello");
let s2 = s1; // s1 is now invalid
// Borrow (immutable)
let s = String::from("hello");
let r = &s; // s is still valid
// Borrow (mutable)
let mut s = String::from("hello");
let r = &mut s;
r.push_str(" world");
Common Errors
| Error |
Fix |
value used after move |
Clone or use reference |
cannot borrow as mutable more than once |
Limit mutable borrow scope |
cannot borrow as mutable because also borrowed as immutable |
Drop immutable refs first |
Mental Model
Owner ──owns──▶ Value
│
├── &T (shared borrow, read-only, many allowed)
└── &mut T (exclusive borrow, read-write, only one)