The Ownership Rules
Ownership is Rust's signature move. It's the machinery that lets the language promise memory safety without ever running a garbage collector.
The Three Rules
- Every value has an owner.
- Exactly one owner at a time.
- When the owner falls out of scope, the value is dropped — freed automatically.
{ let s = String::from("hello"); // s owns the String // s is valid here} // s goes out of scope - String is dropped (memory freed)Move Semantics
Assignment doesn't copy heap-owning values — ownership moves:
let s1 = String::from("hello");let s2 = s1; // ownership moves from s1 to s2
// println!("{}", s1); // ERROR: s1 no longer owns the dataprintln!("{}", s2); // OK: s2 is the ownerA C programmer reading this expects both variables to alias the same buffer — and a careless free on one to nuke the other. Rust forecloses on the entire failure mode: the compiler tracks the move and refuses to let the dead binding speak.
Why Moves?
Picture what happens without moves:
If both s1 and s2 were live, dropping each would free the same heap allocation twice. Classic double-free. Rust shuts the door by invalidating s1 the moment the move happens.
Stack vs Heap
Stack-only types like integers don't move — they're copied:
let x = 5;let y = x; // x is copied, both are validprintln!("{} {}", x, y); // OKIt works because integers implement the Copy trait. Anything trivially copyable — integers, booleans, floats, chars — gets bitwise duplicated. Anything with a heap allocation behind it (String, Vec, your Box-wrapped types) moves.
Functions and Ownership
Passing into a function is also a move:
fn take_string(s: String) { println!("{}", s);} // s is dropped here
let s = String::from("hello");take_string(s);// println!("{}", s); // ERROR: s was moved into the functionReturning hands ownership back the other way — the caller becomes the new owner:
fn give_string() -> String { let s = String::from("hello"); s // ownership moves to the caller}
let s = give_string(); // s now owns the StringThe Ownership Pattern
It can feel cramped at first. The payoff:
- No double frees — only the owner can drop, and there's only one owner.
- No use-after-free — moved-from bindings refuse to compile if you touch them.
- Destruction is deterministic — you know exactly when cleanup runs.
- Cleanup is automatic on scope exit (yes, leaks are still reachable via reference cycles or
mem::forget).
All of it falls out at compile time, and your binary pays nothing for the privilege.
Time to watch the rules fire. impl Drop lets a type run code when it's freed, so Noisy announces each drop. Predict the order of the four lines before you press Run.