Sub topic 2
The Three Ownership Rules
Ownership is the set of rules Rust uses to decide when a value's memory is freed. This chapter assumes you know basic Rust syntax, can run programs with cargo, and have a rough picture of the stack and the heap. It covers the three rules, what they mean in practice, and the edge cases that surprise people. Moves, Drop, and borrowing each get their own chapter, so here they appear only as far as the rules need them.
The rules
- 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.
The terms mean the following:
- A value is a piece of data, such as a
String, aVec<i32>, or a struct instance. - An owner is the variable, struct field, or collection slot that is responsible for that value.
- Dropped means the value's cleanup code runs and any resources it holds, such as heap memory, are released.
fn main() {
let name = String::from("Ferris"); // `name` owns the String
let greeting = format!("Hello, {name}"); // `greeting` owns a new String
println!("{greeting}");
} // `greeting` is dropped first, then `name`Nothing in this program calls a free function. The compiler inserts the cleanup at the closing brace, in reverse order of declaration.
Why three rules are enough
Manual memory management fails in three well-known ways. The rules rule out each one at compile time.
| Bug | What goes wrong | Which rule prevents it |
|---|---|---|
| Leak | Memory is never released | Rule 3: every owner's scope ends, so every value is dropped |
| Double free | Two owners both release the same memory | Rules 1 and 2: only one owner exists, so only one release happens |
| Use after free | Code reads memory that was already released | Rule 3 plus the borrow checker: access ends before the owner's scope does |
The check costs nothing at run time. The compiler tracks owners statically and emits the drop code where each owner's scope ends.
Rule 2 in action: ownership moves
Assigning a non-Copy value to another variable transfers ownership. The original variable stops being a valid owner.
fn main() {
let s = String::from("hello");
let t = s; // ownership moves from `s` to `t`
// println!("{s}"); // error[E0382]: borrow of moved value: `s`
println!("{t}");
}If you uncomment the println! line, the compiler reports an error like this:
error[E0382]: borrow of moved value: `s`
--> src/main.rs:5:16
|
2 | let s = String::from("hello");
| - move occurs because `s` has type `String`, which does not implement the `Copy` trait
3 | let t = s;
| - value moved here
4 | println!("{s}");
| ^^^ value borrowed here after moveThe message gives you three facts: where the value was moved, why it moved (String is not Copy), and where you used it afterwards. Read these three parts of every move error in the same way.
Copying only a pointer, length, and capacity (the String header) would leave two owners of one buffer. The move prevents that. The next chapters cover Copy types and clone, which are the escape hatches.
Rule 3 in action: when drops happen
Drops happen at predictable points, not only at the end of main. The following program uses a type that prints when it is dropped.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
fn main() {
let _x = Noisy("first");
let _x = Noisy("second"); // shadowing does not drop the first value
println!("shadowed");
let mut y = Noisy("y1");
y = Noisy("y2"); // assignment drops the old value, y1, immediately
println!("reassigned");
let _ = Noisy("ignored"); // `_` does not bind, so this drops at once
let _kept = Noisy("kept");
println!("end");
}The output is:
shadowed
drop y1
reassigned
drop ignored
end
drop kept
drop y2
drop second
drop firstFour details are worth remembering:
- Shadowing hides the old name but does not end the old value's life. Both
_xvalues live until the end of the scope. - Assigning to an existing variable drops the value it held before.
- The pattern
_does not bind a value, so a temporary assigned to it is dropped at the end of that statement. The name_keptdoes bind, so that value lives to the end of the scope. - Locals are dropped in reverse order of declaration.
Owners can be fields and elements
An owner is not always a local variable. A struct owns its fields, a Vec owns its elements, and a Box owns the value it points to. Ownership therefore forms a tree. When a parent is dropped, it drops its children.
struct User {
name: String,
tags: Vec<String>,
}
fn main() {
let user = User {
name: String::from("ada"),
tags: vec![String::from("admin")],
};
let name = user.name; // partial move: only `name` leaves `user`
println!("{name}");
println!("{}", user.tags.len()); // `tags` is still owned by `user`
}Moving one field out leaves the other fields usable. You cannot use user as a whole afterwards, and you cannot pass it to a function. This works only because User does not implement Drop. A type with a Drop implementation cannot be partially moved, because its drop method needs the complete value.
What the rules do not promise
Ownership guarantees memory safety, not that every destructor runs.
Two other limits are worth knowing:
- Panics unwind the stack by default, so owners still drop during a panic. With
panic = "abort"inCargo.toml, they do not. - Rules 1 and 2 apply to each value, not to each variable name. Two variables can hold equal data and still be independent owners of separate values, for example after
clone.
A working checklist
When a program fails with a move error, ask these questions in order:
- Which variable owns the value right now?
- Where did ownership leave that variable, such as an assignment, a function call, a
forloop over a collection, or a closure withmove? - Does the later code need ownership, or only to read or change the value? If it only reads, it should borrow, which the next chapters cover.
Exercise
In the program below, which value is dropped first when main ends, and why does println!("{b}") compile?
fn main() {
let a = String::from("one");
let b = a;
let c = String::from("two");
println!("{b}");
}
Show answer
The value "two" is dropped first, because locals drop in reverse order of declaration and c was declared last. The println!("{b}") compiles because b is the current owner after a was moved into it. Using a after line 3 would be the error. The "one" buffer is dropped when b drops, after c.
Exercise
Add one line at the marked comment so the program prints "x1" and then "x2" in that order, using only what this chapter covered. Explain which rule you relied on. struct Noisy(&'static str); impl Drop for Noisy { fn drop(&mut self) { println!("{}", self.0); } } fn main() { let mut x = Noisy("x1"); // add one line here println!("after"); }
Show answer
Add x = Noisy("x2");. Assigning to x drops the old value, so "x1" prints at that line. "after" prints next, and "x2" prints when main ends, so the output is x1, after, x2. This relies on rule 3: when the owner stops owning a value, the old value is dropped. If the output must be only "x1" then "x2" without "after", remove the println!.