Module 04 — Ownership
Goal
The idea the whole language is built on. Moves, copies, drops, and why Rust needs neither a garbage collector nor a manual free.
Start here — the most important module in the course
Everything after this module is a consequence of what is here, so read this orientation before the sections — and be prepared to read the module itself twice.
The problem every language must solve. When your program asks for memory to hold something — say the text a user typed — that memory must eventually be given back. If it never is, the program slowly consumes the machine (a leak). If it is given back while some part of the program is still using it, you get a use-after-free: reading or writing memory that now belongs to something else. That bug is the source of a large share of the security vulnerabilities in the world.
The two existing answers, and what they cost.
- You handle it. C hands you the responsibility. It is fast, and it depends on every programmer getting every path right, forever.
- Something watches at runtime. Java, Go, Python and JavaScript run a garbage collector: a component that periodically works out what is no longer reachable and reclaims it. Safe, and it costs memory, CPU, and pauses you do not schedule.
Rust's answer is neither. It adds three rules to the language itself and checks them while compiling:
- Every value has exactly one owner — a variable responsible for it.
- There can be only one owner at a time.
- When the owner goes out of scope, the value is cleaned up automatically, right there.
Because the compiler can see all three statically, it knows the exact line where every value dies and inserts the cleanup itself. No collector, no pauses, no manual free, and no way to use something after it is gone — the program that would do so does not compile.
What this costs you is the part everyone feels: giving a value to someone else means giving it away. That is called a move, and after a move the original name stops working. It feels wrong for about a week. Then module 05 shows you how to lend instead of give, and it stops being an issue.
The one sentence to remember: exactly one thing owns each value, and when that thing goes out of scope the value is cleaned up — which is why nothing can be used after it is gone.
Note
This is the module. Everything else in Rust is a consequence of what's here. Read it twice.
Learning objectives
- State the three ownership rules and apply them to code
- Trace what happens on assignment, function call, and return
- Distinguish a move from a copy and know which types are
Copy - Explain
Dropand deterministic destruction - Read and fix
E0382: borrow of moved value - Explain why Rust needs neither a garbage collector nor manual
free
4.1 The problem ownership solves
Every language must answer: when is heap memory released?
| Strategy | Language | Cost |
|---|---|---|
Manual malloc/free | C | use-after-free, double-free, leaks — the top source of CVEs |
| Garbage collection | Java, Go, JS, Python | runtime overhead, unpredictable pauses, needs a runtime |
| Reference counting everywhere | Swift, Python | atomic counter traffic, cycles leak |
| Ownership | Rust | compile-time only; zero runtime cost |
Rust's answer: exactly one variable owns each value; when that variable goes out of scope, the value is dropped. The compiler proves this statically. There is no runtime bookkeeping at all — the generated machine code is what a careful C programmer would have written by hand.
Analogy — who takes the bins out
Every language has to answer one household question: who takes the rubbish out, and when? Manual memory management is whoever remembers — and the day nobody does, or two people do, you have a bug. A garbage collector is a cleaner who wanders through at unpredictable moments and tidies whatever nobody is holding. Rust writes it into the tenancy agreement: each item has exactly one named tenant, and it goes out the moment that tenant leaves the room. No forgetting, no wandering cleaner, no pause.
4.2 The three rules
- Each value in Rust has an owner.
- There can be only one owner at a time.
- When the owner goes out of scope, the value is dropped (freed).
fn main() {
{ // s not valid here
let s = String::from("hello"); // s is valid from here
println!("{s}");
} // scope ends: `drop(s)` runs, heap freed
// println!("{s}"); // ❌ E0425: cannot find value `s`
}At the closing brace, Rust automatically inserts a call to String's destructor. This is
called RAII (Resource Acquisition Is Initialization) and it applies to all resources:
files close, sockets shut down, locks release — deterministically, at a point you can see
in the source.
4.3 Move semantics
Stack-only data copies
let x = 5;
let y = x; // i32 is Copy: y gets its own 5
println!("{x} {y}"); // ✅ both validHeap-owning data moves
let s1 = String::from("hello");
let s2 = s1; // MOVE, not a copy
// println!("{s1}"); // ❌ E0382: borrow of moved value: `s1`
println!("{s2}"); // ✅What actually happened:
BEFORE AFTER `let s2 = s1;`
s1 ┌──────────┐ heap s1 ┌──────────┐ heap
│ ptr ─────┼──► "hello" │ ✗ INVALID│ ─┐
│ len 5 │ │ │ │
│ cap 5 │ └──────────┘ │
└──────────┘ s2 ┌──────────┐ ▼
│ ptr ─────┼──► "hello"
│ len 5 │
│ cap 5 │
└──────────┘
The three stack words were bit-copied (cheap), the heap buffer was not copied, and
s1 was marked invalid by the compiler. If both stayed valid, both would be dropped at
scope end → double free. Rust prevents that by invalidating the source.
Mental model
A move is a shallow copy plus the compiler forbidding further use of the source. It costs nothing at runtime; the invalidation is purely a compile-time fact.
The error message is unusually helpful:
error[E0382]: borrow of moved value: `s1`
|
2 | let s1 = String::from("hello");
| -- move occurs because `s1` has type `String`,
| which does not implement the `Copy` trait
3 | let s2 = s1;
| -- value moved here
4 | println!("{s1}");
| ^^^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
Deep copying: clone
let s1 = String::from("hello");
let s2 = s1.clone(); // explicit heap allocation + memcpy
println!("{s1} {s2}"); // ✅ both valid, two separate buffersclone() is always explicit in Rust. Nothing expensive happens implicitly — if you see
an allocation in the profiler, you can find it in the source.
Gotcha
.clone() is the beginner's escape hatch from the borrow checker. That's
fine while learning. But if you're cloning in a hot loop, the right fix is usually
borrowing (module 05), not cloning.
Watch a move happen, step by step
let s1 = String::from("hello");
let s2 = s1;
println!("{s1}"); // ❌ E0382Line by line, in terms of what is physically in memory:
String::from("hello")puts the five characters in the heap, and puts a small record on the stack holding three things: where those characters are, that there are five of them, and how much room was reserved.s1owns that whole arrangement.let s2 = s1;copies the small stack record — three machine words, essentially free. It does not copy the heap characters.- Now two records point at the same heap text. If both stayed valid, both would clean it up when their scope ended, and the second cleanup would free memory that was already freed. So Rust marks
s1as no longer usable. Nothing was deleted, nothing was slowed down; a compile-time fact was recorded. println!("{s1}")therefore refuses to compile — not because usings1would crash today, but because the compiler will not let you build a program in which it might.
Why not just copy the text? Because that would be an allocation and a copy you never asked for, hidden inside an =. Rust's rule is that expensive things stay visible: if you want a genuine duplicate you write s1.clone(), and the cost is right there in the source.
Why is this fine for numbers? let a = 5; let b = a; leaves a perfectly usable, because an i32 owns nothing in the heap. Duplicating it is meaningless and harmless. Types like that are marked Copy — see §4.4.
Analogy — handing over the deed
A move is not photocopying the house; it is signing the deed over. The building never moved an inch — what changed is whose name is on the paperwork, and the old owner's key stops working. That is why moving a String costs nothing at runtime and why using the old binding afterwards is not a crash but a refusal: you are waving a key that is no longer yours.
4.4 Which types are Copy?
A type is Copy if duplicating it is just a bit-copy with no ownership implications —
i.e. it owns no heap memory and has no destructor.
Copy types:
- All integers (
i32,u64,usize, ...) bool,char, all floats- Shared references
&T - Tuples and arrays if every element is
Copy:(i32, bool)isCopy,(i32, String)is not
Not Copy:
String,Vec<T>,Box<T>,HashMap,File- Mutable references
&mut T(there can only be one — copying would break that) - Any type containing a non-
Copyfield - Any type implementing
Drop(a type cannot be bothCopyandDrop)
You can opt your own types in:
#[derive(Debug, Clone, Copy)]
struct Point { x: i32, y: i32 }
let p1 = Point { x: 1, y: 2 };
let p2 = p1; // copy
println!("{p1:?} {p2:?}"); // ✅ both usableCopy requires Clone, always.
Analogy — a banknote versus a house
Some things are trivially duplicated: a £5 value written on a slip of paper can be copied and both slips are equally real — that is Copy. A house cannot be duplicated by copying its address; you would have two deeds to one building. Types that own something out in the warehouse are never Copy, and that is the whole rule.
4.5 Ownership and functions
Passing a value to a function moves it, exactly like assignment:
fn takes_ownership(s: String) {
println!("{s}");
} // s dropped here
fn makes_copy(n: i32) {
println!("{n}");
} // nothing special happens
fn main() {
let s = String::from("hello");
takes_ownership(s);
// println!("{s}"); // ❌ moved into the function
let n = 5;
makes_copy(n);
println!("{n}"); // ✅ i32 is Copy
}Returning transfers ownership back:
fn gives_ownership() -> String {
String::from("yours")
}
fn takes_and_gives_back(s: String) -> String {
s // moved out
}
fn main() {
let s1 = gives_ownership();
let s2 = takes_and_gives_back(s1);
println!("{s2}");
}The tedium this creates (and its fix)
fn calculate_length(s: String) -> (String, usize) {
let len = s.len();
(s, len) // hand the string back so the caller can keep using it
}
let s1 = String::from("hello");
let (s1, len) = calculate_length(s1);This is obviously awful. The fix — borrowing — is the entire next module. Feel the pain now so the solution lands.
The three things a function can do with a value
Every function you write takes one of these three stances toward its arguments, and being deliberate about which is most of what "designing an API in Rust" means:
fn consume(s: String) { } // takes ownership — the caller loses it
fn borrow(s: &String) { } // looks at it — the caller keeps it
fn borrow_mut(s: &mut String) { } // changes it — the caller keeps it- Take ownership when the function genuinely needs to keep or destroy the value — storing it in a structure, sending it to another thread, consuming it to build something else.
- Borrow (
&) when you only need to read. This is the overwhelmingly common case, and it is the subject of module 05. - Borrow mutably (
&mut) when you need to modify the caller's value in place.
Right now only the first of these exists for you, which is why §4.5's examples look tedious — passing a String in and returning it straight back out just to keep using it. That tedium is real, and module 05 exists entirely to remove it. Feel it here so the fix lands properly there.
4.6 Partial moves
You can move a field out of a struct, invalidating only that field:
struct Person { name: String, age: u32 }
let p = Person { name: String::from("Ada"), age: 36 };
let name = p.name; // partial move
// println!("{}", p.name); // ❌ moved
println!("{}", p.age); // ✅ age is Copy and wasn't moved
// println!("{}", p.name.len()) // ❌
// let q = p; // ❌ cannot move out of partially moved valueDestructuring does the same thing, which is why let Person { name, age } = p; consumes
p.
4.7 Drop — deterministic destruction
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 end");
}
println!("outer scope end");
}Output:
inner scope end
dropping b
outer scope end
dropping a
Values drop in reverse declaration order (LIFO), and inner scopes drop first. You
cannot call .drop() yourself (that would allow a double free); use std::mem::drop(x)
to drop early:
let s = String::from("bye");
drop(s); // freed here
// println!("{s}"); // ❌This is why Rust needs no finally, no defer, no with, and no try-with-resources:
scope exit is the cleanup mechanism, and it runs even during a panic unwind.
Analogy — the lease ends on a known date
A garbage collector is a landlord who eventually notices the flat is empty. Drop is a lease with an end date written into it: at that exact line, the keys come back, the utilities are closed, the file handle is released. Deterministic destruction is why Rust needs no finally block — the cleanup is attached to the value, not to your discipline.
4.8 Why this is the whole ballgame
Ownership gives you, simultaneously:
- Memory safety without GC. No dangling pointers because a value can't outlive its owner; no double free because there's only one owner.
- Data-race freedom. A data race needs two threads accessing the same memory with at least one writing. Ownership plus borrowing (next module) makes that impossible to express safely — this is what "fearless concurrency" means (module 17).
- Predictable performance. No pauses, no background threads, no allocation you didn't write.
Jargon buster
Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.
| Term | In plain English |
|---|---|
| owner | The single variable responsible for a value's cleanup. |
| move | Transferring ownership. The source binding becomes unusable; nothing is copied beyond a small stack record. |
Copy | A marker for types duplicated by a plain bit-copy — numbers, bool, char, and tuples of those. Assignment leaves the original usable. |
Clone | An explicit, possibly expensive, deep duplicate. You always write .clone() yourself. |
| drop | The automatic cleanup that happens when an owner goes out of scope. |
| scope | The region between braces where a binding exists. |
Drop | The trait letting a type run custom code when it is dropped — closing a file, releasing a lock. |
| use-after-free | Reading memory that has already been reclaimed. Impossible in safe Rust. |
| double free | Reclaiming the same memory twice. What the move rule prevents. |
| partial move | Moving one field out of a struct, which makes only that field unusable while the rest stays valid. |
If you get stuck
The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.
| What you see | What it means | What to do |
|---|---|---|
error[E0382]: borrow of moved value | You used a value after giving it away. | Three options, best first: borrow instead (&s, module 05); return the value back out of the function; or s.clone() if you genuinely need two. |
error[E0382]: use of moved value | The same cause, usually inside a loop — the value moved on the first iteration. | Borrow inside the loop, or move it in deliberately with into_iter() if consuming really is what you meant. |
error[E0507]: cannot move out of borrowed content | You tried to take ownership of something you only had on loan. | Work with the reference, or .clone() it if you must own a copy. |
"I keep writing .clone() everywhere" | Not an error, but a signal. | Cloning to silence the borrow checker is a normal learning stage. After module 05, come back and replace them with borrows. |
Now make it stick: work through the drills for this module, then carry on to Module 05 — Borrowing, References & Slices.
