The Analogy: The Cloakroom Ticket
The cloakroom at a concert hall. You hand over your coat, an attendant hangs it on hook 12, and you get one small paper ticket with "12" printed on it. There is exactly one ticket for that coat -- not two, not a spare behind the counter. The coat is on the hook; the ticket is in your pocket; and the ticket is emphatically not the coat. It is a few grams of paper that happens to be the only way to reach several kilograms of wool.
Now give the ticket to a friend. That is a trivial act -- you hand over a slip of paper, not a coat -- and it is exactly as fast whether the coat is a windbreaker or a floor-length overcoat. But notice what has happened to you: you can no longer collect that coat. Not "should not". Cannot. The attendant releases the coat to whoever presents ticket 12, and there is one ticket. The rule is not politeness, it is arithmetic.
When you leave, you present the ticket, the coat comes off the hook, and hook 12 is free for the next person. Nobody has to remember to free the hook; it happens as a consequence of you leaving. And nobody can present ticket 12 for a coat that has already gone, because the ticket went with it. The system has no way to release the same coat twice and no way to leave a hook occupied by a coat whose owner has gone home.
This is Rust's ownership model, essentially unchanged. A String variable is the ticket; the heap buffer holding the bytes is the coat on the hook. Writing let b = a; hands the ticket to b, and a becomes unusable -- as a compile error, checked before the program runs, not a null check that fires later. When the owning variable goes out of scope, Rust inserts the call that frees the buffer, exactly once. There is no garbage collector scanning for coats nobody wants, and no free() for you to forget or to call twice. And values small enough to fit entirely on the ticket -- an i32, a bool, a char -- are Copy: the attendant just writes the number on a second slip, because there is no coat on a hook for anyone to fight over.
Syntax or Core Structure
Ownership has no keyword. It shows up in five ordinary places: a scope ending, an assignment, a function call, a return, and .clone().
fn main() {
// 1. Scope. The value is dropped at the closing brace.
{
let s = String::from("hook 12");
println!("inside: {s}");
} // s goes out of scope here; its heap buffer is freed.
// 2. Assignment moves ownership for non-Copy types.
let a = String::from("coat");
let b = a;
println!("b = {b}");
// println!("a = {a}"); // error[E0382]: a was moved into b
// 3. Copy types are duplicated instead, so both stay usable.
let x = 5;
let y = x;
println!("x = {x}, y = {y}");
// 4. Passing to a function moves, exactly like assignment does.
let owned = String::from("ticket");
consume(owned);
// println!("{owned}"); // error[E0382]: owned was moved into consume
// 5. Returning hands ownership back out.
let made = produce();
println!("made = {made}");
// 6. clone() is the explicit, possibly expensive opt-out.
let original = String::from("duplicate me");
let copy = original.clone();
println!("original = {original}, copy = {copy}");
}
fn consume(s: String) {
println!("consume got {s}");
} // s is dropped here, at the end of the function that owns it.
fn produce() -> String {
String::from("fresh")
}
Output:
inside: hook 12
b = coat
x = 5, y = 5
consume got ticket
made = fresh
original = duplicate me, copy = duplicate me
Now uncomment one line and read what the compiler says, because this diagnostic is the one you will meet most often in your first month of Rust:
fn main() {
let a = String::from("coat");
let b = a;
println!("a = {}", a);
}
Output (compile error):
error[E0382]: borrow of moved value: `a`
--> src/main.rs:4:24
|
2 | let a = String::from("coat");
| - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 | let b = a;
| - value moved here
4 | println!("a = {}", a);
| ^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let b = a.clone();
| ++++++++
Read the three underlines in order: where the value came from and why it is not Copy, where ownership left, and where you tried to use it afterwards. That is the whole story of every move error, and the compiler tells it the same way every time. The help is worth noticing too -- it suggests clone() while explicitly naming the cost, because clone() is the right answer sometimes and the lazy answer often.
Technical Depth: Moves, Copy, and When Drop Runs
The three rules
- Every value in Rust has exactly one owning variable.
- There can be only one owner at a time. Assigning, passing, or returning transfers ownership.
- When the owner goes out of scope, the value is dropped and its resources are released.
That is the entire model. Everything else in this lesson is a consequence.
Move or copy? The type decides, not the syntax
let b = a; is one syntax with two behaviours, chosen by whether a's type implements the Copy marker trait:
| Category | Examples | let b = a; does |
|---|---|---|
Copy | every integer and float, bool, char, &T, and tuples or arrays whose elements are all Copy | Duplicates the bits. a stays usable |
Not Copy | String, Vec<T>, Box<T>, HashMap, &mut T, anything with a Drop impl, any struct with a non-Copy field | Moves. a is statically dead from that line on |
Two entries there catch experienced programmers out. A shared reference &T is Copy -- you can hand out as many as you like -- while a mutable reference &mut T is not, which is the mechanism behind "only one mutable borrow at a time" in the next lesson. And a type cannot be both Copy and Drop: try it and you get error[E0184]: the trait Copy cannot be implemented for this type; the type has a destructor. That prohibition is not arbitrary. If a value were duplicated freely and had a destructor, the destructor would run once per duplicate and release the same resource several times.
What a move actually costs
A move copies the value's stack representation and nothing else. For a String that is three words -- pointer, capacity, length -- and the heap bytes are not read, written, or reallocated:
use std::mem::size_of;
fn main() {
println!("String = {} bytes", size_of::<String>());
println!("Vec<u8> = {} bytes", size_of::<Vec<u8>>());
println!("&String = {} bytes", size_of::<&String>());
println!("Box<u64> = {} bytes", size_of::<Box<u64>>());
println!("Option<Box> = {} bytes", size_of::<Option<Box<u64>>>());
println!("i32 = {} bytes", size_of::<i32>());
}
Output (on a 64-bit target; these are platform-specific):
String = 24 bytes
Vec<u8> = 24 bytes
&String = 8 bytes
Box<u64> = 8 bytes
Option<Box> = 8 bytes
i32 = 4 bytes
So moving a one-byte String and moving a one-gigabyte String cost the same 24 bytes, and the optimiser usually removes even that. This is why "pass by value" is not a performance warning sign in Rust the way it is in C++: handing over a String is handing over a ticket. Option<Box<u64>> is 8 bytes rather than 16 because Box can never be null, so the compiler uses the all-zeroes pattern to mean None -- the niche optimisation.
When Drop runs, and in what order
Rust's destructor is the Drop trait, and the rules are worth knowing precisely because they are what make RAII patterns (file handles, locks, transactions) work without a finally block:
- Locals are dropped at the end of their scope, in reverse declaration order.
- Struct and enum fields are dropped in declaration order, after the containing value's own
dropruns. - A value that was moved away is not dropped by the original scope. The new owner is responsible.
drop(x)is not a keyword. It is an ordinary function whose entire body is empty and which takes its argument by value -- so calling it moves the value in, and the value dies at the end ofdrop.
Instrument it and watch:
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn take(n: Noisy) {
println!("take received {}", n.0);
}
fn main() {
let _first = Noisy("first");
let _second = Noisy("second");
{
let _inner = Noisy("inner");
println!("-- inner scope ending");
}
let moved = Noisy("moved");
take(moved);
println!("-- after take");
let early = Noisy("early");
drop(early);
println!("-- main ending");
}
Output:
-- inner scope ending
dropping inner
take received moved
dropping moved
-- after take
dropping early
-- main ending
dropping second
dropping first
Three things to read out of that trace. moved is dropped inside take, not in main -- ownership moved, so responsibility moved. early dies at the drop(early) call rather than at the end of main, which is how you release a lock or close a file at a chosen moment. And the last two lines are second then first, reverse declaration order, because a value declared later may hold a reference to one declared earlier and must therefore die first.
The underscore prefix in _first matters, too, and not in the way most people assume. _first is a perfectly ordinary variable whose name happens to start with an underscore; the prefix only silences the unused-variable warning. A bare _ is different -- it is a pattern that binds nothing, so let _ = Noisy("gone"); drops the value on that very line. That distinction is the difference between holding a mutex guard for a whole function and releasing it immediately.
What a signature promises
Because ownership travels through calls, a function signature is a contract about lifecycle before it is anything about types:
| Signature | What the caller learns |
|---|---|
fn f(s: String) | Hand it over and forget it. f will drop it or pass it on |
fn f(s: &String) | f only reads it; you keep it |
fn f(s: &mut String) | f may change it; you keep it |
fn f() -> String | f gives you something new to own |
fn f(s: String) -> String | Take-and-give-back. Almost always a sign &mut was wanted |
The last row is the shape beginners write to escape move errors, and it works, but it forces the caller into let s = f(s); at every call. References, in the next lesson, are the actual answer.
Real World Example: A Pipeline That Cannot Be Run Backwards
Text arrives, gets normalised, then gets rendered. In most languages that is three variables sitting in the same scope and a code-review convention that says "do not read raw after normalising". In Rust it is three types and three signatures, and the convention becomes a compile error.
/// Text exactly as it arrived -- from a file, a request body, stdin.
struct Raw(String);
/// Text after normalisation. Taking `Raw` by value is the point: once you
/// have a `Clean`, the un-normalised original no longer exists.
struct Clean {
lines: Vec<String>,
}
/// The finished artefact.
struct Report {
body: String,
words: usize,
}
fn normalise(raw: Raw) -> Clean {
let lines = raw
.0
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.collect();
Clean { lines }
}
fn render(clean: Clean) -> Report {
let words = clean.lines.iter().map(|l| l.split_whitespace().count()).sum();
let body = clean.lines.join(" / ");
Report { body, words }
}
fn main() {
let raw = Raw(String::from(
"# heading to drop\n first line \n\n \nsecond line here\n# another comment\n third ",
));
let clean = normalise(raw);
// `raw` is gone. No later line can read the un-normalised text,
// because there is nothing left to read it from.
println!("kept {} lines", clean.lines.len());
let report = render(clean);
// `clean` is gone too, and its line buffers were freed inside `render`.
println!("words = {}", report.words);
println!("body = {}", report.body);
}
Output:
kept 3 lines
words = 6
body = first line / second line here / third
The signature fn normalise(raw: Raw) -> Clean is a statement about lifecycle, not just about types. It says: give me the raw text, you will not be getting it back, and here is a different thing in exchange. So the bug class "somewhere further down, a maintainer reads the raw body instead of the cleaned one" is not something to catch in review -- the identifier does not resolve. Ownership converted a discipline problem into a compiler problem, which is the trade Rust makes over and over.
The newtypes are doing half the work. Raw(String) and Clean { lines } hold the same characters in different arrangements, but they are distinct types, so render(raw) does not compile even though the data would be "close enough". Pair distinct types with by-value parameters and you get a pipeline that can only be walked forwards, and only once. This is the plain version of a pattern Rust libraries lean on heavily: encode the stage in the type so the wrong stage cannot be passed.
Deallocation is scheduled by the code's shape rather than by a collector's opinion. normalise allocates fresh Strings -- trim().to_string() has to -- and the Raw it consumed is dropped the moment normalise returns, so the original buffer is released before render ever runs. Then Clean dies at the end of render, freeing all three line buffers, and only Report survives into the rest of main. Peak memory is two stages, never three, and nothing had to be reference-counted or scanned to arrange that.
That last point is the practical difference from a garbage-collected version of the same pipeline. There, whether the raw text is still alive is a property of the whole program: if any variable anywhere still refers to it, it stays. Here it is a property of this one function, readable from its signature, and enforced. The cost is that you have to decide who owns what -- which is genuinely more thinking up front, and is the reason the next two lessons exist, because most of the time what you actually want is to lend a value rather than give it away.
Common Mistakes
- Using a value after passing it to a function.
consume(s); println!("{s}");iserror[E0382]. The fix is usuallyconsume(&s)plus a&in the signature, nots.clone()-- read the next lesson before reaching for the clone.
- Assuming
let b = a;copies. It depends entirely on the type, and nothing in the syntax tells you which happened.let b = a;on ani32copies; on aStringit moves; on(i32, String)it moves, because one non-Copyfield makes the whole tuple non-Copy.
- Using
.clone()as a compile-error silencer. It works and it is sometimes correct, but aclone()inside a loop is an allocation per iteration. Ask first whether a shared reference would do; reach forclonedeliberately, and preferably with a comment saying why.
- Moving a field out of a struct you still need whole. After
let items = page.items;you have partially movedpage, and any method taking&selfon it fails witherror[E0382]: borrow of partially moved value. Either take the field last, or usestd::mem::taketo swap in a default.
- Expecting a moved value to still be dropped where it was declared. It is not.
take(moved)meansmoved's destructor runs insidetake. If your destructor has an observable effect -- flushing a buffer, releasing a lock, committing a transaction -- then where you pass the value is when that effect happens.
- Thinking
Copymeans cheap.[u8; 4096]isCopy, so every assignment memcpys four kilobytes with no syntax to warn you. Large arrays are exactly where an accidental copy hides, because the borrow checker will not object.
- Trying to derive
Copyon a type that owns something. A struct with aStringfield giveserror[E0204]: the trait Copy cannot be implemented for this type, and a type with aDropimpl giveserror[E0184]. Both are the compiler refusing to let one resource be released twice.
- Confusing
let _ = value;withlet _name = value;. The first drops immediately; the second holds the value to the end of the scope. With aMutexGuardthis is the difference between no locking at all and correct locking, and both versions compile.
- Writing
fn f(s: String) -> Stringto dodge move errors. It compiles, but it pusheslet s = f(s);onto every call site and makes every intermediate step re-bind. When you find yourself doing this more than once, the answer is&mut.
Best Practices
- Decide who owns each value once, early, and write it down in the signatures. Ownership questions answered at design time are cheap; answered by fighting the borrow checker at 5pm, expensive.
- Take parameters by reference by default and by value only when the function genuinely needs to keep or consume the value.
fn parse(text: &str) -> Configis almost always better thanfn parse(text: String) -> Config.
- Return owned values rather than references wherever you can. Handing out a
Stringcosts 24 bytes on the stack and frees the caller from thinking about lifetimes.
- Treat every
.clone()as a decision worth a comment. In a hot loop it is a bug; at a module boundary where two owners are genuinely required, it is the correct tool.
- Use
Dropfor anything that must be released, and let scope do the releasing. If you find yourself writing aclose()that callers must remember to call, you have re-invented the bugDropexists to prevent.
- Reach for
std::mem::takeorstd::mem::replacewhen you need to move a field out of a struct you still own. Both leave the struct valid instead of partially moved.
- Encode pipeline stages as distinct types when the stages must not be confused.
Raw,Clean,Validatedcost one line each and make the wrong order unrepresentable.
- Read the three underlines in an
E0382before changing anything: what was moved, where it moved, where you used it after. The fix is almost always at the second underline, not the third.
Practice Exercises
- Predict the drops. Take the
Noisyprogram above and add aVec<Noisy>containing three elements, plus a structPair { left: Noisy, right: Noisy }. Before running it, write down the exact order of every "dropping" line you expect, then run it and reconcile any differences. Pay particular attention to whether theVecdrops its elements front-to-back.
- Cost out a move. Write a function that builds a
Stringof one million characters, then moves it through five functions that each take it by value and return it. Time the whole thing withstd::time::Instant, then change one function to takeStringand returns.clone()instead, and time it again. Report the ratio rather than the absolute numbers, since those are machine-specific.
- Escape a partial move. Given
struct Job { name: String, payload: Vec<u8> }, write a function that takes&mut Job, removes and returns the payload, and leaves the job with an empty payload -- without cloning and without partially moving. Then write a second version takingJobby value that returns both the name and the payload as a tuple.
- Break the pipeline on purpose. In the
Raw/Clean/Reportexample, try each of these and record the exact error code: printingraw.0afternormalise(raw); callingrender(clean)twice; changingnormaliseto take&Rawand seeing what breaks in the body; adding#[derive(Clone)]toRawand usingnormalise(raw.clone())so the original survives. Then argue in two sentences which version you would ship.