Deep Dive: Rust Ownership
Rust's ownership model is what makes it unique among systems languages. In this article we'll walk through the three rules, with examples.
The Three Rules
- Each value has a single owner.
- When the owner goes out of scope, the value is dropped.
- You can have either
- one mutable reference, or
- any number of immutable references
A First Example
Consider this code:
fn main() {
let s = String::from("hello");
takes_ownership(s);
}
fn takes_ownership(s: String) {
println!("{}", s);
}
Comparison Table
| Operation | Stack | Heap | Notes |
|---|---|---|---|
| Copy | implicit (Copy) | requires .clone() | primitive types only on stack |
| Move | — | invalidates source | default for String, Vec… |
| Borrow | cheap | cheap | checked at compile time |
"Ownership is Rust's most unique feature." — The Rust Book