Ownership
Part 1 · Rust. Learn Rust's big idea, ownership, through café analogies: stack vs heap, the three rules, moves, and clone, explained gently.
Welcome to the lesson that makes Rust Rust. Ownership is the idea most new Rustaceans find tricky at first, and that’s completely normal. We’re going to take it slowly, one small step at a time, using our coffee shop, the Rusty Bean Café, as the example. By the end you’ll know what the compiler is protecting you from, and why it sometimes says “no”.
Take a breath. You don’t need to understand everything on the first read. Most people understand ownership by meeting it a few times, and this is your first meeting.
Why does Rust need ownership?
Every program uses your computer’s memory to store things: a customer’s name, a list of orders, a price. When the program is done with a piece of data, that memory should be given back, so it can be used again.
Different languages handle this in different ways:
- Some languages (like C) make you free the memory yourself. Forget, and memory leaks. Free it twice, and the program can crash.
- Some languages (like Python or JavaScript) use a garbage collector, a helper that runs in the background, looks for data nobody uses any more, and cleans it up. Easy, but it costs some speed and you don’t control when it runs.
Rust picks a third way: ownership. A small set of rules, checked by the compiler before your program runs, decides exactly when each piece of data is cleaned up. No garbage collector and no manual freeing, and a whole family of memory bugs can’t happen.
The stack and the heap, in plain words
Rust stores data in two areas of memory. You don’t need the deep details, only the feeling of each.
The stack: a stack of trays
Picture the stack of trays by the café counter. You put a tray on top and you take a tray off the top. It’s fast and tidy, but every tray is the same, known size.
The stack holds data whose size is known ahead of time and never changes: numbers like u32, bool, char, and small fixed things. A price of 450 cents always fits in exactly the same space.
The heap: the storage room
Now picture the café’s back storage room. When a big delivery arrives and you don’t know in advance how much space it needs, you find a free spot on the shelves, put it there, and write down where you put it on a sticky note.
The heap holds data that can grow or whose size isn’t known in advance, like a String. A customer’s name could be "Al" or "Maximiliana". The actual letters live in the heap, and on the stack Rust keeps a small sticky note (called a pointer) that says where the letters are, plus their length.
Note
You don’t choose “stack” or “heap” by hand in everyday Rust. Types decide it for you. Numbers live on the stack, and a String keeps its text on the heap. Ownership mainly matters for heap data like String.
The three rules of ownership
Here they are. Read them once now; we’ll look at each one with code.
- Each value in Rust has an owner, a variable that is responsible for it.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped (cleaned up).
A good café analogy: a value is like a coffee order ticket. Exactly one barista holds a ticket at a time. When that barista’s shift ends, any ticket they’re still holding is thrown away.
Rule 1 and 3: owners and scope
A scope is the area of code where a variable is valid, usually between a pair of curly braces { }.
fn main() { { let drink = String::from("Latte"); // drink starts here println!("Making a {drink}"); } // scope ends: drink is dropped here
// println!("{drink}"); // error: drink no longer exists}Step by step:
String::from("Latte")creates aStringon the heap. The variabledrinkis its owner.- We can use
drinkinside the inner braces. - At the closing
},drinkgoes out of scope. Rust automatically drops it and gives the heap memory back. You didn’t write any cleanup code.
Making a LatteRule 2: one owner at a time (moves)
Now the part that surprises people. Look at this:
fn main() { let order = String::from("Cappuccino"); let ticket = order;
println!("Ticket: {ticket}"); println!("Order: {order}"); // this line will not compile}In many languages this would print “Cappuccino” twice. In Rust, the compiler stops you:
error[E0382]: borrow of moved value: `order` --> src/main.rs:6:23 |2 | let order = String::from("Cappuccino"); | ----- move occurs because `order` has type `String`, which does not implement the `Copy` trait3 | let ticket = order; | ----- value moved here...6 | println!("Order: {order}"); // this line will not compile | ^^^^^ value borrowed here after move |help: consider cloning the value if the performance cost is acceptable |3 | let ticket = order.clone(); | ++++++++What happened? let ticket = order; did not copy the text “Cappuccino”. It moved ownership from order to ticket. Think of handing the order ticket to another barista: you no longer have it in your hand.
How to read the error calmly:
- The headline:
borrow of moved value: order. You usedorderafter it was moved. - Line 2 note: it tells you why a move happens:
Stringdoesn’t implementCopy(more on that below). - Line 3 note: “value moved here” points at exactly where ownership left.
- Line 6 arrow:
^^^^^points at the line where you tried to use it anyway. (The...just means the compiler skipped some lines that don’t matter.) - help: the compiler even suggests one possible fix,
.clone(). We’ll look at what that does in a moment.
Tip
Rust error messages tell a little story from top to bottom: what went wrong, where it started, and where it hurt. Read the lines with notes first. You can also run rustc --explain E0382 for a longer explanation.
Why move instead of copy?
Remember the sticky note? A String on the stack is just a pointer, a length and a capacity. The length is how many bytes of text it holds right now. The capacity is how much room it has reserved on the heap, like a shelf space that can fit a few more boxes before you need a bigger shelf. If Rust copied only the sticky note, two variables would point at the same heap memory. When both went out of scope, Rust would try to clean up the same memory twice. That’s a classic, dangerous bug called a double free.
By moving, Rust makes sure only one variable is ever responsible for cleaning up. One ticket, one barista.
Moves into functions
Passing a value to a function moves it too, exactly like let:
fn brew(drink: String) { println!("Brewing a {drink}...");} // drink is dropped here
fn main() { let favourite = String::from("Flat White"); brew(favourite); // favourite was moved into brew, so we can't use it here}brew(favourite)moves ownership of theStringinto the parameterdrink.- When
brewfinishes,drinkgoes out of scope and the text is dropped. - Back in
main,favouriteis no longer usable.
Functions can also give ownership back by returning a value:
fn add_extra_shot(drink: String) -> String { format!("{drink} + extra shot")}
fn main() { let order = String::from("Americano"); let order = add_extra_shot(order); println!("{order}");}Americano + extra shotformat! works like println!, but instead of printing the text it builds a brand-new String and hands it back to you.
Ownership went into the function and a new String came back out, owned by the new order. It works, but passing things back and forth gets tiring. The next lesson shows a much nicer tool called borrowing.
Making a real copy with clone
Sometimes you really do want two independent copies. For that, call .clone():
fn main() { let order = String::from("Mocha"); let ticket = order.clone();
println!("Ticket: {ticket}"); println!("Order: {order}");}Ticket: MochaOrder: Mocha.clone() makes a deep copy: new heap memory with the same letters. Now there are two owners of two separate values, so both are valid.
Warning
A common beginner habit is adding .clone() everywhere to make errors go away. It works, but each clone copies data, which can slow a program down. Cloning is fine while you learn. Over time, reach for borrowing (next lesson) first.
Copy types: the small exception
You may wonder why this works fine:
fn main() { let price_cents: u32 = 450; let total = price_cents;
println!("Price: {price_cents}, total: {total}");}Price: 450, total: 450Simple types with a known, fixed size live entirely on the stack, and copying them is cheap. These types implement a trait called Copy (you’ll learn about traits later). When you assign them, Rust copies the value instead of moving it.
Common Copy types: all integers (u32, i64, …), floats (f64), bool, char, and tuples made only of these, like (u32, bool). String is not Copy.
Putting it together at the café
fn print_receipt(item: String, price_cents: u32) { println!("{item}: ${}.{:02}", price_cents / 100, price_cents % 100);}
fn main() { let item = String::from("Blueberry Muffin"); let price_cents: u32 = 300;
print_receipt(item.clone(), price_cents); print_receipt(item, price_cents); // item is moved now, but price_cents is Copy and still usable println!("Price was {price_cents} cents");}Blueberry Muffin: $3.00Blueberry Muffin: $3.00Price was 300 cents- The first call passes a clone, so
itemstays ours. - The second call moves
itemin. After that,itemcan’t be used. price_centsis au32, aCopytype, so it’s copied each time and stays usable.{:02}pads the cents with a zero, so 5 cents prints as05.
Important
If ownership still feels fuzzy, that’s okay. Remember three words: owner, move, drop. The compiler will remind you of the rest, and its messages will start to feel helpful rather than scary.
Try it yourself
- This code doesn’t compile. Fix it two different ways: once with
clone, and once by changing the order of the lines.
fn main() { let customer = String::from("Priya"); let loyalty_name = customer; println!("Welcome back, {customer}!"); println!("Card holder: {loyalty_name}");}Show solution
Fix 1, clone the value:
fn main() { let customer = String::from("Priya"); let loyalty_name = customer.clone(); println!("Welcome back, {customer}!"); println!("Card holder: {loyalty_name}");}Fix 2, use customer before it moves:
fn main() { let customer = String::from("Priya"); println!("Welcome back, {customer}!"); let loyalty_name = customer; println!("Card holder: {loyalty_name}");}- Write a function
label(drink: String) -> Stringthat returns the drink name with" (large)"added. Call it frommainand print the result.
Show solution
fn label(drink: String) -> String { format!("{drink} (large)")}
fn main() { let drink = String::from("Chai Latte"); let drink = label(drink); println!("{drink}");}Ownership moves into label, and a new String is returned and owned by the new drink.
Recap
- Rust frees memory automatically using ownership, checked at compile time. There’s no garbage collector.
- Fixed-size data lives on the fast stack. Growable data like
Stringkeeps its contents on the heap. - The rules: every value has one owner, and the value is dropped when its owner goes out of scope.
- Assigning or passing a
Stringmoves it. The old variable can’t be used any more. .clone()makes a real copy. SmallCopytypes likeu32are copied automatically.
What’s next
Moving values around all the time is clumsy. In Borrowing and References you’ll learn how to lend a value without giving it away.
0 of 35 lessons complete