Ownership Rules
In this page:
The Three Ownership Rules
Rust's ownership system rests on three rules: each value has one owner, there can only be one owner at a time, and when the owner goes out of scope, the value is dropped. These rules are enforced entirely at compile time.
Example: The Three Ownership Rules
fn main() {
let owner = String::from("Rust");
println!("{} is owned by this variable", owner);
}
Login to try C/C++/Java/PHP code in the editor
Scope and Automatic Cleanup
When an owning variable goes out of scope, Rust automatically calls cleanup code to free its memory. This happens deterministically, without a garbage collector, right when the closing brace of its scope is reached.
Example: Scope and Automatic Cleanup
fn main() {
{
let temp = String::from("temporary");
println!("Inside scope: {}", temp);
}
println!("temp has been dropped by now");
}
Login to try C/C++/Java/PHP code in the editor
Only One Owner at a Time
Because a value can only have one owner, assigning it to another variable transfers (moves) ownership rather than creating a second independent owner. This prevents two variables from both trying to free the same memory.
Example: Only One Owner at a Time
fn main() {
let a = String::from("hello");
let b = a; // ownership moves from a to b
println!("b owns the value: {}", b);
}
Login to try C/C++/Java/PHP code in the editor
Why This Matters
These rules eliminate whole categories of bugs -- like double frees and use-after-free -- that are common in languages with manual memory management, without needing a garbage collector at runtime.
Example: Why This Matters
fn main() {
let data = vec![1, 2, 3];
println!("data is owned here and will be cleaned up automatically: {:?}", data);
}
Login to try C/C++/Java/PHP code in the editor
- Assuming a value can have two independent owners at once -- Rust's core rule is exactly one owner at a time.
- Trying to use a variable after its value has been moved elsewhere, which the compiler rejects at compile time.
- Thinking ownership rules only apply to heap-allocated types like
String-- they apply to all values, though simple types are alsoCopy.
- Every value in Rust has exactly one owner variable at any given time.
- When the owner goes out of scope, Rust automatically drops (frees) the value.
- Ownership can be transferred (moved) to another variable, after which the original binding is no longer valid.
- These rules are checked entirely at compile time, with zero runtime overhead.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: