Sub topic 1
Ownership and borrowing: the rules smart pointers bend
This chapter reviews the ownership and borrowing rules that the rest of the tutorial depends on. Smart pointers such as Box, Rc, and RefCell each relax one of these rules in a controlled way. To follow that, you need the rules fresh in mind, along with the exact point where the compiler enforces each one.
Prerequisites
This chapter assumes you already know the following:
- Rust ownership, moves, and the basic borrowing rules.
- References and lifetimes at a basic level.
- Structs, enums, and pattern matching.
- Traits and generics at a basic level.
- The difference between stack and heap memory.
If a term below is unfamiliar, revisit the relevant part of the Rust book before continuing.
The three ownership rules
Rust's memory safety rests on three rules:
- Every value has exactly one owner.
- There is only one owner at a time.
- When the owner goes out of scope, the value is dropped.
Rule 3 is why Rust needs no garbage collector. The compiler inserts the cleanup call at the end of the owner's scope. Rules 1 and 2 are why that cleanup is safe, because no second owner can free the same memory.
fn main() {
let a = String::from("hello");
let b = a; // ownership moves from a to b
// println!("{a}"); // error[E0382]: borrow of moved value: `a`
println!("{b}");
} // b is dropped here, and the String's heap buffer is freedAfter the move, a is no longer usable. The compiler tracks this statically, so there is no runtime cost.
A type that implements Copy, such as i32 or bool, is the exception. Assigning it copies the bits and both variables stay valid. Types that own heap memory cannot be Copy, because two owners would free the same buffer twice.
The borrowing rules
Borrowing lets you use a value without taking ownership. There are two kinds of reference, and the rules are:
- At any given time, you can have either one mutable reference (
&mut T) or any number of shared references (&T). - References must always be valid. A reference cannot outlive the value it points to.
The first rule is often summarized as "aliasing XOR mutability". Many readers can share a value, or one writer can change it, but never both at once.
fn main() {
let mut scores = vec![10, 20, 30];
let first = &scores[0]; // shared borrow
// scores.push(40); // error[E0502]: cannot borrow `scores` as mutable
println!("first = {first}");
scores.push(40); // fine: the shared borrow ended after its last use
println!("{:?}", scores);
}The commented-out push is rejected because push may reallocate the vector. That would leave first pointing at freed memory. The rule exists to prevent exactly this bug.
When the checks happen
The borrow checker runs at compile time. It reasons about scopes and lifetimes without running the program. This has two consequences that matter for the rest of the tutorial:
- Violations are compile errors, so a program that compiles cannot break these rules.
- The checker is conservative. It must reject any program it cannot prove safe, including some programs that would be safe at runtime.
That second point is the opening that smart pointers use. Some valid designs cannot be expressed with plain references. Each smart pointer moves one check or one rule to a different place.
The diagram below summarizes where each pointer sits relative to the compile-time rules.
Which rule each type bends
The table maps each pointer to the rule it changes. Later chapters cover each one in detail.
| Type | Rule it relaxes | What replaces the compile-time guarantee |
|---|---|---|
| `Box<T>` | Values of unknown size cannot be stored inline | A fixed-size pointer to heap data. Ownership stays single. |
| `Rc<T>` | One owner at a time | A reference count that frees the value when it reaches zero. |
| `RefCell<T>` | Borrow rules are checked at compile time | The same rules checked at runtime, with a panic on violation. |
| `Cell<T>` | Mutation requires `&mut` | Copying values in and out, so no reference to the contents exists. |
Notice that Box is the gentlest of these. It does not change the ownership rules at all. It only changes where the data lives. Rc and RefCell genuinely relax the rules, and each pays for that with a cost: a counter to maintain, or a runtime check that can fail.
A limit that plain references cannot cross
Here is a concrete case where the compile-time rules get in the way. You want two variables to own the same vector, and you want to change it through one of them.
fn main() {
let data = vec![1, 2, 3];
let first_owner = data;
// let second_owner = data; // error[E0382]: use of moved value: `data`
println!("{:?}", first_owner);
}With plain ownership, the second line cannot compile because the first let moved the value. Borrowing offers a way around this, since both users could hold &data. Borrows come with restrictions, though. Shared references give read-only access. A mutable reference must be unique. A reference cannot outlive its owner either, so it cannot keep the data alive on its own.
The designs that hit this wall are usually the following:
- A graph or tree where several nodes point to the same child.
- A shared cache or configuration that several components must keep alive.
- A mock object or observer that records calls through a method taking
&self.
Each needs one of the rules above to be relaxed. The relaxation has to stay safe, so it needs an explicit mechanism, and the mechanism is a smart pointer.
Compile-time errors versus runtime failures
When you reach for a smart pointer, you often trade a compile-time error for a runtime risk. Knowing which risk you are taking helps you pick the right tool.
Boxadds no new runtime failure. A heap allocation can fail only when memory runs out.Rcadds reference cycles. TwoRcvalues that point to each other are never freed. This is a leak, not undefined behavior, and Rust treats leaks as safe.RefCelladds a panic. Breaking the borrow rules at runtime stops the thread with a message such asalready borrowed: BorrowMutError.
None of these breaks memory safety. A smart pointer cannot cause a use-after-free or a data race in safe code. What you give up is the guarantee that the compiler found every mistake before the program ran.
Checking your understanding
Use these points as a checklist before moving on. You should be able to state each one without looking back.
- What the three ownership rules are, and why the compiler can drop values without a garbage collector.
- What "aliasing XOR mutability" means, and which bug it prevents.
- Why the borrow checker rejects some programs that would be safe.
- Which rule
Box,Rc, andRefCelleach relax, and what each one costs.
Exercise
The borrow checker rejects let first = &v[0]; v.push(4); println!("{first}");. Name the rule that is broken and explain why the rule exists.
Show answer
It breaks the rule that you may have either one mutable reference or any number of shared references, never both at once. push needs &mut v while first still holds a shared borrow that is used afterward. The rule exists because push can reallocate the vector's buffer, which would leave first pointing at freed memory.
Exercise
Of Box, Rc, and RefCell, which one does not relax the single-owner rule or move the borrow checks to runtime? What does it change instead?
Show answer
Box. It keeps a single owner and keeps compile-time borrow checking. It changes only where the data is stored, putting it on the heap and leaving a fixed-size pointer on the stack.