Sub topic 1
Rust Ownership: Stack, Heap, and Manual Memory
Prerequisites
This chapter assumes basic Rust syntax, functions, String, and Vec, plus a general idea of the stack and heap.
Why Ownership Exists
The stack stores small, fixed-size values. It is fast because values are added and removed in a predictable order. The heap stores data with a size or lifetime that can change, such as a String's text.
In languages with manual memory management, a programmer allocates heap memory and later frees it. Forgetting to free it causes a memory leak. Freeing it twice causes a double free. Using it after freeing it causes a use-after-free.
Rust prevents these errors at compile time. Ownership records which part of a program is responsible for each value.
The Three Ownership Rules
Rust's ownership model has three rules:
- Each value has exactly one owner.
- Only one owner exists at a time.
- When the owner leaves its scope, Rust drops the value.
A scope is the region between matching braces. Dropping means releasing resources automatically.
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");
}The inner value is dropped when its block ends. The outer value is dropped when main ends. The Drop trait lets a type define cleanup behavior.
> callout note > Ownership applies to resources, not only memory. A type can use Drop to close a file, release a lock, or perform other cleanup.
Moves
Assigning a heap-owning value usually moves ownership instead of copying its data:
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// println!("{s1}"); // error: s1 was moved
println!("{s2}");
}After the move, s1 cannot be used. This prevents two variables from independently freeing the same allocation.
Copy and Clone
Small types such as integers implement Copy, so assignment copies their value:
fn main() {
let a = 5;
let b = a;
println!("{a} {b}");
let s1 = String::from("hi");
let s2 = s1.clone();
println!("{s1} {s2}");
}Clone makes an explicit, potentially expensive duplicate. Use it when two independent owned values are required.
Exercise
After let y = String::from("x"); let z = y;, which variable owns the string?
Show answer
z owns it. y was moved and cannot be used.