8 / 35

Core Rust Concepts· 14 min read· Lesson 8 of 35

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.

  1. Each value in Rust has an owner, a variable that is responsible for it.
  2. There can only be one owner at a time.
  3. 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 { }.

src/main.rs
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:

  1. String::from("Latte") creates a String on the heap. The variable drink is its owner.
  2. We can use drink inside the inner braces.
  3. At the closing }, drink goes out of scope. Rust automatically drops it and gives the heap memory back. You didn’t write any cleanup code.
Output
Making a Latte

Rule 2: one owner at a time (moves)

Now the part that surprises people. Look at this:

src/main.rs
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:

Output
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` trait
3 | 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:

  1. The headline: borrow of moved value: order. You used order after it was moved.
  2. Line 2 note: it tells you why a move happens: String doesn’t implement Copy (more on that below).
  3. Line 3 note: “value moved here” points at exactly where ownership left.
  4. 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.)
  5. 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:

src/main.rs
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
}
  1. brew(favourite) moves ownership of the String into the parameter drink.
  2. When brew finishes, drink goes out of scope and the text is dropped.
  3. Back in main, favourite is no longer usable.

Functions can also give ownership back by returning a value:

src/main.rs
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}");
}
Output
Americano + extra shot

format! 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():

src/main.rs
fn main() {
let order = String::from("Mocha");
let ticket = order.clone();
println!("Ticket: {ticket}");
println!("Order: {order}");
}
Output
Ticket: Mocha
Order: 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:

src/main.rs
fn main() {
let price_cents: u32 = 450;
let total = price_cents;
println!("Price: {price_cents}, total: {total}");
}
Output
Price: 450, total: 450

Simple 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é

src/main.rs
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");
}
Output
Blueberry Muffin: $3.00
Blueberry Muffin: $3.00
Price was 300 cents
  1. The first call passes a clone, so item stays ours.
  2. The second call moves item in. After that, item can’t be used.
  3. price_cents is a u32, a Copy type, so it’s copied each time and stays usable.
  4. {:02} pads the cents with a zero, so 5 cents prints as 05.

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

  1. 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}");
}
  1. Write a function label(drink: String) -> String that returns the drink name with " (large)" added. Call it from main and 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 String keeps 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 String moves it. The old variable can’t be used any more.
  • .clone() makes a real copy. Small Copy types like u32 are 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

Search lessons

Type to search all lessons.