Lesson 4.2 · 8 min
One owner, one key
Every piece of data in a Rust program has exactly one owner, like a room with a single key. This one idea is what Rust is famous for, and once you can picture it the rest of the chapter is easy.
Adds to ChatterboxThe mental model; no code change.
The one-key rule
Lesson 4.1 ended on a job that must be done exactly once: every heap block has to be handed back, never zero times (a leak) and never twice (a crash). Some languages leave that job to you; others hire a helper that runs alongside your program. Rust settles it with one rule, checked while compiling, and everything else in this chapter hangs off it.
Picture each value as a room, and each room has exactly one key. Whoever holds the key owns the room, and is the one responsible for emptying it. That is the whole model:
- Every value has exactly one owner. Usually the owner is a variable (later you will see a value owned by a list or by another value, but the rule is the same).
- When the owner goes away, the value is cleaned up. The key is thrown out and the room is emptied: for a String, its heap block is handed back.
Two more things can happen to a key, and they get a lesson each. As a preview: you can hand it over to a new owner, or lend it out for a while. Those are the two moves you will use most. When you truly need two separate rooms, you can also make a copy of one (called a clone), which you meet in the next lesson.
Watch a key appear and go
Here is a small program with two variables, one inside a pair of braces. The braces make a scope: a stretch of code where a name exists. Step through it. It is the same picture as lesson 4.1, frames on the stack and blocks on the heap, and from now on a solid arrow from a variable to a heap block reads as owns.
Step through the program. Solid arrows are ownership; dashed arrows are borrows. Use ← → or the slider.
- Line 1. The program starts in main. Its variables will live in this frame.
- Line 2. A String is made: 24 bytes in main's frame, its text in a heap block. The variable msg owns that block: msg holds the key.
- Line 4. Inside the braces a second String is made. note is its one owner.
- Line 5. note is used while it still exists. This prints scratch. stdout:
scratch - Line 6. The closing brace ends the scope. note goes away, so its text is cleaned up right here. You wrote no code for that; Rust put it in.
- Line 7. msg is still in scope, so it still owns its text and can use it. This prints hi chatterbox. stdout:
hi chatterbox - Line 8. main ends, so msg goes away and its text is cleaned up too. Everything that was made has been cleaned up, exactly once.
That cleanup at the closing brace is why you never write "free this memory" in Rust. Each value is cleaned up exactly once, at a place you can point to: the line where its one owner goes out of scope. So you cannot forget to clean up, and you cannot clean up twice. (Memory that is never handed back is called a leak, and a Rust program can still leak, but rarely: it takes special tools, such as shared ownership that is counted while the program runs, or a function whose whole job is to keep memory forever. Forgetting a line of cleanup is never the cause, because there is no line to forget.)
Try the next one before you read the answer. The program uses a name outside the braces where it was made.
Does this compile — and if it does, does it run?
- It compiles and runs
- Compile error E0425
- Compile error E0382
Reveal the answer
It does not compile: E0425. The braces end the scope, so the name note does not exist on the next line. The compiler says it cannot find the value. The owner is gone, and so is the room.
error[E0425]: cannot find value `note` in this scope --> src/main.rs:5:16 | 5 | println!("{note}"); | ^^^^ | help: the binding `note` is available in a different scope in the same function --> src/main.rs:3:13 | 3 | let note = String::from("scratch"); | ^^^^
Why one key?
A program that frees memory twice, or uses it after it was freed, crashes or opens a security hole. Those bugs happen when two parts of a program both think they are in charge of the same data. The one-key rule makes that impossible: only one owner, so only one cleanup, and a name whose key is gone cannot be used.
Some other languages avoid the same bugs a different way: while the program runs, they keep count of how many names point at each value and clean up when the count hits zero. That is a fine design. Rust does the bookkeeping while compiling instead, before the program ever runs, so the finished program has no counting to do.
If you have coded before
In Python, b = a makes two names for one object, and either can change it. In Rust, for text like this, let b = a; hands the key to b and a stops working. The next lesson shows it. It feels strict for a day, then it feels like a seatbelt.
Keys can leave through a return
A function can make a value and give its key to whoever called it. The value is the function's result. Nothing is cleaned up, because the owner changed instead of going away. The hand-over has to happen while the owner still exists, though: after its closing brace there is no key left to give.
A warm-up, separate from Chatterbox. goodbye builds a goodbye card, bye, then the name then !, and should hand it to whoever called it. Right now it builds the card inside a pair of braces and tries to return it after the closing brace. Press Run first and read the error, then fix it so the key leaves through the return instead of being thrown away at the brace.
A warm-up, separate from Chatterbox. goodbye builds a goodbye card, bye, then the name then !, and should hand it to whoever called it. Right now it builds the card inside a pair of braces and tries to return it after the closing brace. Press Run first and read the error, then fix it so the key leaves through the return instead of being thrown away at the brace.
Hidden tests (3): the_card_names_the_person an_empty_name_still_gets_a_card every_caller_owns_its_own_card
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
What you have now
Chatterbox has no new code in this lesson: the program is exactly as lesson 3.4 left it, and you can unfold it further down, after the self-check. Look at it with new eyes, though. In the table from lesson 4.1, name_line and line each had a heap block. Now you can say who holds those keys: the two variables, in main's frame. When main ends, they go away and both blocks are handed back, once each, with no line of yours. name and message point into those blocks too, but they hold no key, so nothing is handed back twice. What you have now is the rule behind every later line: one value, one owner, cleaned up when the owner goes. Next, what happens when you want to give the key to somebody else.
Say it out loud, then reveal
State the one-key rule in a sentence.Reveal
Where exactly is a variable's text cleaned up?Reveal
How can a function give a new value to its caller?Reveal
Your Chatterbox so far: v0.3 (after lesson 3.4)
Download this version (zip)Unzip, then cargo run inside the folder.
That is lesson 4.2. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What is ownership in Rust?
Ownership is the rule that every value has exactly one owner, usually a variable. When the owner goes out of scope, Rust cleans the value up automatically, exactly once.
Does Rust have a garbage collector?
No. Rust works out at compile time where each value is cleaned up, which is the point where its owner goes out of scope, so nothing has to scan memory while the program runs.
What is a scope in Rust?
A scope is a stretch of code, usually between a pair of curly braces, where a name exists. When the scope ends, the names made inside it go away and the values they own are cleaned up.
Can Rust programs leak memory?
They can, but it is rare and takes special tools, such as shared ownership that is counted while the program runs (two such values that point at each other are never cleaned up), or a function that deliberately keeps memory forever. Ordinary code cannot forget to free memory or free it twice, because each value is cleaned up when its owner goes away.