Level 1 · Foundations· Lesson 4 of 10 · 25 min
Ownership
The three rules that let Rust free memory without a garbage collector — and why a moved value cannot be used again.
This is the lesson that makes Rust Rust. Take it slowly and run every example.
The problem
A program’s memory comes in two kinds. The stack holds values whose size is known at compile time; it is freed automatically when a function returns. The heap holds data whose size can change, like a growing string. Someone has to decide when heap memory is released.
- Free too early, and something still pointing at it reads garbage: use-after-free.
- Free twice: double free, heap corruption.
- Never free: a leak.
Garbage-collected languages solve this by tracing at runtime. C solves it by trusting you. Rust solves it with a compile-time discipline.
The three rules
- Every value has exactly one owner (a variable, a field, an element of a collection…).
- There is only one owner at a time.
- When the owner goes out of scope, the value is dropped — its memory and any other resources are released.
fn main() {
{
let s = String::from("hello"); // s owns a heap buffer
println!("{s}");
} // s goes out of scope here → the buffer is freed
// println!("{s}"); // s no longer exists
}
No free, no collector. The compiler inserts the cleanup at the closing brace.
Moves
A String is three words on the stack — a pointer, a length, and a capacity — plus a buffer on the heap. What should let b = a; do?
If it copied only the three words, two variables would point at one buffer and both would try to free it. If it copied the buffer too, every assignment would be a hidden allocation. Rust does neither: it copies the three words and then considers a invalid. Ownership has moved.
fn main() {
let a = String::from("hello");
let b = a; // ownership moves from a to b
println!("{b}");
println!("{a}"); // ❌ error[E0382]: borrow of moved value: `a`
}
Run it and read the error. The compiler shows where the value moved and where you tried to use it afterwards. This single check eliminates double frees and use-after-free: there is always exactly one owner responsible for cleanup.
A move costs a few machine words regardless of how big the heap data is. It is never a deep copy.
Clone: an explicit deep copy
When you really do want two independent copies, ask for it:
fn main() {
let a = String::from("hello");
let b = a.clone(); // allocates a new buffer and copies the bytes
println!("{a} {b}");
}
.clone() is visible in the source, so expensive copies never hide. When you are learning, reaching for clone to get past an error is fine. Later you will learn when a borrow is the better tool.
Copy: types that are just bits
Integers do not behave like String:
fn main() {
let a = 5;
let b = a;
println!("{a} {b}"); // both fine
}
Types that live entirely on the stack and own nothing implement the Copy trait. Assigning them duplicates the bits and leaves the original valid. Copy types include all integers and floats, bool, char, and tuples or arrays made only of Copy types. Anything that owns a heap allocation — String, Vec, Box — is not Copy.
Ownership and functions
Passing a value to a function moves it, exactly like assignment. Returning a value moves it out.
fn consume(s: String) {
println!("consumed: {s}");
} // s is dropped here
fn make() -> String {
String::from("fresh") // ownership moves to the caller
}
fn main() {
let a = String::from("hello");
consume(a);
// println!("{a}"); // ❌ a was moved into consume
let b = make();
println!("{b}");
}
Having to hand a value back every time you want to keep using it would be unbearable:
fn length(s: String) -> (String, usize) {
let n = s.len();
(s, n) // give ownership back, along with the answer
}
fn main() {
let s = String::from("hello");
let (s, n) = length(s);
println!("{s} has {n} bytes");
}
This works, but nobody writes Rust this way. The next lesson introduces borrowing: letting a function use a value without taking ownership of it.
Drop order
Values are dropped in the reverse order of their declaration. You can watch it happen:
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");
{
let _c = Noisy("c");
}
println!("end of main");
}
This pattern — tying cleanup to scope — is called RAII. In Rust it manages memory, files, locks and network connections alike.
Exercises
- Fix this program in two different ways (once with
clone, once by reordering lines):let s = String::from("x"); let t = s; println!("{s} {t}"); - Write
fn shout(s: String) -> Stringthat returns the string in upper case (to_uppercase()). Call it and print the result. What happens to the argument? - Predict the output of the drop-order example if you add
drop(_a);(the standard function that takes ownership and drops) beforelet _b.
Solution to 3
dropping a is printed first, immediately at the drop call, then dropping c, end of main, dropping b. drop is nothing special: it is a function that takes its argument by value and lets it fall out of scope.
Check your understanding
Pick an answer to see the explanation.
1.After
let a = String::from("hi"); let b = a;, which bindings are usable?2.After
let a = 5; let b = a;, which bindings are usable?3.When is a
String's heap buffer freed?