Sub topic 2
The Three Ownership Rules
This chapter assumes you can read basic Rust syntax (variables, functions, structs), run programs with cargo, and that you know the general difference between the stack and the heap. Here you learn the rules that the rest of Rust's memory model depends on.
The rules
Rust manages memory without a garbage collector. It does this by checking, at compile time, who owns each value. Three rules define ownership:
- Each value in Rust has exactly one owner.
- There can be only one owner at a time.
- When the owner goes out of scope, the value is dropped.
A value is a piece of data, such as a String or an integer. The owner is the variable that holds it. Rule 3 says that when the variable's scope ends, Rust frees the value's memory automatically.
Why the rules exist
Manual memory management has three classic bugs. Each rule closes one of them.
| Bug | What goes wrong | How the rules prevent it |
|---|---|---|
| Leak | Memory is never freed | Rule 3: the owner's scope end always triggers a drop |
| Double free | Two owners both free the same memory | Rules 1 and 2: only one owner exists, so only one drop runs |
| Use after free | Code reads memory that was already freed | The compiler rejects use of a value after its owner has given it up or gone out of scope |
All of this is checked when you compile. At run time there is no extra bookkeeping.
The rules in code
The program below shows rule 3. Noisy implements the Drop trait, which lets you run code at the moment a value is dropped.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let _a = Noisy("a");
{
let _b = Noisy("b");
println!("inner scope ends");
}
println!("main ends");
}It prints:
inner scope ends
dropping b
main ends
dropping a_b lives in the inner block, so it is dropped when that block ends. _a lives in main, so it is dropped last.
Rule 2 in action
Assigning one variable to another transfers ownership. This is called a move. The old variable is no longer valid.
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// println!("{s1}"); // error: borrow of moved value: `s1`
println!("{s2}");
}After let s2 = s1;, s2 is the single owner. If both variables still owned the string, both would try to free it at the end of main. That would be a double free. The compiler prevents it by rejecting any later use of s1.
Common mistakes
- Using a variable after moving it. The error message says "borrow of moved value". Fix it by borrowing instead of moving, or by cloning the value.
- Expecting every type to move. Simple types such as integers are copied instead. Later chapters cover
CopyandClone. - Thinking a drop happens at the last use. A value is dropped when its owner's scope ends, not when it was last read.
Exercise
A function creates let v = vec![1, 2, 3]; let w = v; and then prints v. Which ownership rule does the compiler enforce when it rejects this, and how many times is the vector's memory freed if you remove the print?
Show answer
It enforces the rule that a value has only one owner at a time. After the move, w is the owner and v is invalid. If you remove the print, the memory is freed exactly once, when w goes out of scope.