Contents
Ownership is one of Rust’s most distinctive features — and one of the hardest for newcomers.
Ownership trips up most Rust beginners. The examples below show what it is, why the compiler cares, and how move, borrow, and lifetimes fit together. Skim once for the map; come back for the line-by-line bits.
Tip: The code has comments. You don’t need every detail on the first pass — follow the flow, then dig into specific snippets later.
Move or copy?
Let’s see what ordinary assignment looks like in Rust.
1 | println!("start"); |
You get:
1 | error[E0382]: use of moved value: `d` |
Why does code 2 fail when code 1 doesn’t?
Both look like “assign this value to another variable more than once” — once for the number a, once for the string d. Only the string case breaks.
That’s Rust’s split between copying a value and moving ownership.
When you pass a value to another variable or function: if the type implements Copy, Rust duplicates it; otherwise ownership moves.
a is an integer; integers are Copy, so code 1 compiles.
d is a String; strings are not Copy. The first assignment moves ownership to _e. You only get one move, so code 2 fails.
Why copy or move at all? Spoiler: Rust has no garbage collector (GC). Memory is tied to ownership — whoever owns a value is responsible for freeing it when the value is dropped.
Let’s watch that in code.
Scopes and dropping
Focus on when things get destroyed.
1 | // Wrap String so we can impl Drop on our own type (orphan rule) |
Output:
1 | Dropping MyData with value: MyString("not used") |
There are two scopes here:
Tip: There are actually more — each
letis its own scope too. I’m only naming two to keep the story simple.
The scope of
mainitselfAn inner block inside
mainInside the inner block, the
MyDatabound to_(and its string) is dropped.let _means the binding is intentionally ignored and can’t be used again, so it’s dropped right away.When you leave the inner block,
_wrapperis dropped as well.
Together with “strings can’t be moved twice,” you get two pillars of Rust’s memory story:
- A value has exactly one owner; when the owner leaves the scope, the value is dropped.
- Ownership can be transferred.
That model makes manual memory management tractable.
What if you only want to refer to a value without moving it? Moves are one-shot, after all.
Borrowing
A normal “reference” first:
1 | println!("start"); |
This compiles.
Tip: Rust catches a lot of problems at compile time. That’s why you never saw
"start"printed in the earlier failure — compilation stopped first.
Rust splits “references” further; here we call it borrowing (Borrow). We’ll see why in a bit.
From this snippet, one borrow of a string can be assigned to many variables — handy when you don’t need to move the whole String, just read through it.
When is a borrow reclaimed?
1 | // Struct that holds a borrow |
Output:
1 | End of the scope inside main. |
Borrows are dropped before the owned value. You can have many borrows (specifically immutable borrows — more on that soon), but when the owner is dropped, every borrow goes with it. That’s how Rust avoids use-after-free.
Mutation
We haven’t mutated anything yet.
Can you reassign like in other languages?
1 | let d = String::from("hello"); |
No:
1 | error[E0384]: cannot assign twice to immutable variable `d` |
Rust separates read from write. As the hint says, you need mut:
1 | let mut d = String::from("hello"); |
What does drop look like then?
1 | fn main() { |
Output:
1 | Dropping MyString with value: "used as mut variable1" |
Much like immutable bindings — except after reassignment the old value is dropped first. Memory accounting is granular.
We’ve seen borrowing and mut. Borrowing itself has another flavor: the mutable borrow.
Mutable borrows
A mutable binding can have a mutable borrow:
1 | let mut d = String::from("hello"); |
Can you mix mutable and immutable borrows like this?
1 | fn main() { |
No:
1 | error[E0502]: cannot borrow `d` as mutable because it is also borrowed as immutable |
The compiler is explicit: while a mutable borrow is active, you can’t also hold immutable borrows.
Think read–write lock: a mutable borrow is like holding the write lock — no concurrent readers, or your writes and their reads could disagree.
Borrowing rules, summarized:
- You can have many immutable borrows.
- At most one mutable borrow at a time, and it excludes immutable borrows.
Ownership rules
All three ownership principles are on the table now:
- Each value has exactly one owner; when the owner leaves its scope, the value is dropped.
- Ownership can be transferred.
- Borrowing:
- Many immutable borrows allowed.
- One mutable borrow at a time (exclusive with immutable borrows).
These rules define who owns a value, when memory can be freed, and what mutation and sharing are allowed — no dangling use-after-free, and no torn reads during writes (no data races on shared data in the single-threaded borrow-checker sense).
The striking part: the compiler enforces this before you ship. Crashes in production with a late stack trace are worse.
Ownership isn’t done yet — two more ideas: interior mutability and lifetimes.
Interior mutability
So far a borrow is either read-only or write-only — strict. What if you want “mostly read-only” but occasionally mutate through the same handle?
You can.
Rust offers Cell (for Copy types), RefCell (any type; borrow checks at runtime), Arc (thread-safe reference counting), and friends. Mutex and RwLock are the multithreaded face of the same idea.
Tip: Think of these as different granularities of read/write exclusion — mutation without an
&mutin your API surface, but mutability inside.
RefCell in action:
1 | use std::cell::RefCell; |
Lifetimes
Last topic: lifetimes.
Why doesn’t this compile?
1 | fn longest(str1: &str, str2: &str) -> &str { |
Error:
1 | error[E0106]: missing lifetime specifier |
Two borrowed parameters, one borrowed return — the compiler can’t tell which input the return might outlive.
Enter lifetimes: annotations that describe how long references must remain valid, so borrows don’t dangle.
If inputs and output share one lifetime 'a, the returned reference can’t live longer than both inputs — as long as the inputs are valid, the return is valid. If the return could point at something created only inside the function, it would become a dangling pointer after the function returns.
You can picture a lifetime as an extra parameter on a reference, telling the compiler whether that reference is still in-bounds for a given scope.
Side note: Go’s escape analysis solves a related problem — values that must survive the stack frame get heap-allocated. That’s also lifetime reasoning, but with a GC underneath. Rust prefers compile-time lifetime proofs; Box helps when you need heap ownership across scopes (not expanded here).
Does every reference need a label?
No. The compiler infers lifetimes in most code. You only add them when inference clashes. For the deep end, see Subtyping and Variance.
This failing example shows why explicit lifetimes matter for scope checks:
1 | fn get_longest<'a>(str1: &'a str, str2: &'a str) -> &'a str { |
Error:
1 | error[E0597]: `str1` does not live long enough |
Summary
Wrapping up:
- Ownership is about who owns values and when memory is freed.
- The borrow checker enforces that borrows are valid at compile time.
- Lifetimes describe how long references must stay alive.
Together they give Rust strong memory safety without a GC — fewer leaks, fewer dangling pointers, and less runtime overhead from collection.
If you’re curious, the ownership story is worth the learning curve: one coherent model instead of implicit rules scattered across the language.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
