How can two cashiers hold the same menu board, when in Rust every value may have only one owner? Or how can you change stock that many people are borrowing? The strict ownership and borrowing rules have an official way out: the smart pointer. A smart pointer is a value that acts like a pointer to data somewhere else. Unlike a reference, a smart pointer also owns that data, and it has extra abilities. String and Vec are smart pointers too. This lesson covers the three you'll use most yourself: Box, Rc and RefCell.
All three are easy to remember through the back storeroom of Rusdi's Pancake Stall:
- Box is a locker. The goods (the data) are kept in the storeroom (the heap), the cashier just holds the key (the pointer), and whoever holds the key is the owner.
- Rc is the menu board two cashiers use at once. In its corner there's a tally of how many people are still using it (the number of owners). The board is only taken down (thrown away) when the last one is done.
- RefCell is the stock book watched by a supervisor. Anyone may ask to write in it, but the supervisor checks right away that no two people write at the same time. In code, this check happens while the program runs, not at compile time.
Box: data on the heap, one owner
This program puts one price on the heap with Box. 32u32 means the number 32 with the type u32:
fn main() {
let price = Box::new(32u32);
let total = *price * 2;
println!("{} {}", price, total);
println!("{}", std::mem::size_of::<Box<u32>>());
}
32 64
8
Box::new(32u32)puts the number on the heap. Only its pointer lives on the stack, 8 bytes.std::mem::size_of::<Box<u32>>()gives that size in bytes: 8.*pricereads the value inside the Box (a dereference, as in the borrowing lesson).println!doesn't need the*.- A Box has one owner, just like a
String. A move hands over the key to a new owner. When the owner leaves its scope, the contents on the heap are thrown away too.
Box is used for three things:
- types whose size can't be calculated at compile time (next section),
- values whose type is only known while the program runs, like the tray
Vec<Box<dyn Price>>in the traits lesson (total 107), - big data you want to move without copying it.
Recursive types need a Box
Picture a stack of slips on the spike: each slip holds a price and the rest of the stack below it. Written as an enum Stack with a variant Slip(u32, Stack), this type contains itself (a recursive type), and the compiler refuses it:
error[E0072]: recursive type `Stack` has infinite size
--> src/main.rs:1:1
|
1 | enum Stack {
| ^^^^^^^^^^
2 | Slip(u32, Stack),
| ----- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
Rust must know the size of every type at compile time. Slip(u32, Stack) holds a Stack, which holds a Stack again, with no end, so its size is infinite. The compiler's advice: add indirection, that is, a pointer to somewhere else, such as a Box. With a Box, a Slip holds just a price and an 8-byte pointer, and the rest of the stack lives on the heap:
use Stack::{Empty, Slip};
enum Stack {
Slip(u32, Box<Stack>),
Empty,
}
fn total(t: &Stack) -> u32 {
match t {
Slip(price, rest) => price + total(rest),
Empty => 0,
}
}
fn main() {
let stack = Slip(102, Box::new(Slip(70, Box::new(Slip(38, Box::new(Empty))))));
println!("{}", total(&stack));
}
It prints 210. use Stack::{Empty, Slip}; lets the variants be written without Stack::. total calls itself for the rest of the stack, until Empty (0): 102 + 70 + 38 + 0.
Rc: many owners, one piece of data
Sometimes one piece of data really is owned by several parties, and it isn't clear who finishes last. Rc<T> (reference counted, which means its owners are counted) stores the data once. In this program, impl Drop prints one line when the menu board is thrown away:
use std::rc::Rc;
struct Menu {
name: String,
}
impl Drop for Menu {
fn drop(&mut self) {
println!("{} taken down", self.name);
}
}
fn main() {
let menu = Rc::new(Menu { name: String::from("Menu board") });
println!("owners: {}", Rc::strong_count(&menu));
let cashier1 = Rc::clone(&menu);
{
let cashier2 = Rc::clone(&menu);
println!("owners: {}", Rc::strong_count(&menu));
println!("cashier2 reads {}", cashier2.name);
}
println!("owners: {}", Rc::strong_count(&menu));
drop(menu);
println!("owners: {}", Rc::strong_count(&cashier1));
println!("cashier1 reads {}", cashier1.name);
}
owners: 1
owners: 3
cashier2 reads Menu board
owners: 2
owners: 1
cashier1 reads Menu board
Menu board taken down
Rc::clone(&menu)doesn't copy the board, it only adds one owner: the count goes from 1 to 2 (cashier1), then to 3 (cashier2). WritingRc::clone(&menu)rather thanmenu.clone()makes it clear this step is cheap.Rc::strong_count(&menu)reads the number of owners.cashier2leaves its scope at the}, so the count drops to 2.drop(menu)(a built-in function that throws a value away before its scope ends) throws away one more owner, so the count is 1.- The board is only thrown away when the last owner is done.
Menu board taken downprints at the very end, aftercashier1leaves its scope at the end ofmain. - The data inside an Rc can only be read. If
cashier1were anRc<u8>,*cashier1 -= 2would be refused with E0594cannot assign to data in an `Rc`. The reason: if many owners could write freely, the borrowing rule (many readers, or one writer) would no longer hold. - Rc is for one thread only. For many threads there's
Arc, in the section "Arc and Mutex for threads".
RefCell: borrow rules checked while running
This program keeps the egg stock inside a RefCell, then takes some eggs from the stock:
use std::cell::RefCell;
fn main() {
let egg_stock = RefCell::new(250u8);
*egg_stock.borrow_mut() -= 2;
println!("stock: {}", egg_stock.borrow());
}
It prints stock: 248. The variable egg_stock isn't mut, yet its contents change. This is called interior mutability (the contents can change from the inside). borrow_mut() gives a borrow for writing, and borrow() gives a borrow for reading. The rules are the same as in the borrowing lesson: many readers, or one writer. The difference is that they're checked while the program runs, not at compile time.
Now two cashiers take the stock at once. cashier1 takes egg_stock.borrow_mut(). Before cashier1 is done, cashier2 also takes egg_stock.borrow_mut(). Does it compile? If it does, what happens when it runs? Guess before you look at the result:
use std::cell::RefCell;
fn main() {
let egg_stock = RefCell::new(250u8);
let mut cashier1 = egg_stock.borrow_mut();
*cashier1 -= 2;
let mut cashier2 = egg_stock.borrow_mut();
*cashier2 -= 2;
println!("stock: {}", egg_stock.borrow());
}
thread 'main' (25675696) panicked at src/main.rs:7:34:
RefCell already borrowed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
It compiles, then panics on line 7, the second borrow_mut(). The compiler can't see inside a RefCell, so it accepts this code. The check only happens while the program runs, like the supervisor checking right away: when the second borrow_mut() is called, cashier1 still holds its borrow. The other way round works the same: a borrow() while there's still a writer ends in the panic RefCell already mutably borrowed. A borrow from a RefCell lives until the variable that holds it (here cashier1) leaves its scope, so keep the borrow as short as you can. In *egg_stock.borrow_mut() -= 2;, the borrow ends on that same line. To check without a panic, use egg_stock.try_borrow_mut(): while another borrow is still held, it gives Err(BorrowMutError).
Rc<RefCell>: a shared stock that can change
Rc gives many owners, and RefCell gives permission to write. Together, two cashiers can hold and change the same stock:
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let egg_stock = Rc::new(RefCell::new(250u8));
let cashier1 = Rc::clone(&egg_stock);
let cashier2 = Rc::clone(&egg_stock);
*cashier1.borrow_mut() -= 2;
*cashier2.borrow_mut() -= 2;
println!("egg stock: {}", egg_stock.borrow());
println!("owners: {}", Rc::strong_count(&egg_stock));
}
egg stock: 246
owners: 3
Each cashier sells one Egg Pancake that uses 2 eggs, and both see the same stock number: 250, 248, then 246. There are three owners: egg_stock, cashier1 and cashier2. The same approach is used for structures like a graph (points called nodes, joined by lines called edges), where one node is owned by many edges. The node is an Rc<T>, or an Rc<RefCell<T>> if the node needs to change.
Weak, briefly
If two Rcs point at each other (for example, an order points at its customer and the customer points at the order), the count never drops to 0, and the data is never thrown away. As a result, its memory is never given back to the system. This is called a memory leak. Weak<T> is a pointer that isn't counted as an owner. let glance = Rc::downgrade(&menu); makes a Weak from menu: Rc::strong_count stays 1, and Rc::weak_count becomes 1. glance.upgrade() gives Some(...) as long as the data still exists, and None after the last owner has thrown it away. Use Weak for the direction that points back, like a child pointing at its parent.
Arc and Mutex for threads, briefly
Rc counts its owners in a way that isn't safe when two threads change the count at the same time. That is why the compiler refuses to send an Rc to another thread: error[E0277]: `Rc<u8>` cannot be sent between threads safely. The version of Rc for many threads is Arc<T> (atomic reference counted: the count is safe for many threads to change at the same time). RefCell's partner for many threads is Mutex<T>: a lock that makes other threads wait for their turn instead of panicking. The program below runs two kitchen threads that both take eggs from the stock:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let egg_stock = Arc::new(Mutex::new(250u8));
let mut kitchen = Vec::new();
for _ in 0..2 {
let stock = Arc::clone(&egg_stock);
kitchen.push(thread::spawn(move || {
*stock.lock().unwrap() -= 2;
}));
}
for d in kitchen {
d.join().unwrap();
}
println!("egg stock: {}", egg_stock.lock().unwrap());
}
It prints egg stock: 246. Each kitchen thread holds its own Arc, handed over through move (from the closures lesson). thread::spawn runs the closure in a new thread, and join() waits for that thread to finish. lock() makes sure only one thread writes at a time. Threads are covered in more depth outside this track.
Choosing a smart pointer
| Need | Use |
|---|---|
Data on the heap, one owner (recursive types, dyn Trait) |
Box<T> |
| Many owners, one thread, read only | Rc<T> |
| Many owners, many threads, read only | Arc<T> |
| Changing through a plain borrow, one thread | RefCell<T> |
| Many owners and changeable, one thread | Rc<RefCell<T>> |
| Many owners and changeable, many threads | Arc<Mutex<T>> |
⚠️ Smart pointers that get refused, panic, or never get dropped
- A recursive type without a Box. E0072
recursive type ... has infinite size. Wrap the repeating part:Box<Stack>. - Changing through an Rc. E0594
cannot assign to data in an `Rc`, or E0596 for methods likepush_str. UseRc<RefCell<T>>. - Holding a
borrow_mut()too long. It compiles, then panics withRefCell already borrowedwhile the program runs. Borrow, change and finish on one line. - An Rc sent to another thread. E0277
`Rc<u8>` cannot be sent between threads safely. UseArc, andArc<Mutex<T>>if the contents must change. - Rcs pointing at each other. Their data is never thrown away. Make one direction
Weak.
TL;DR: A smart pointer is a value that points to data and also owns it. Box<T> puts data on the heap with one owner, and its pointer is 8 bytes. Box is used for recursive types (types that contain themselves, refused with E0072 without a Box) and dyn Trait. Rc<T> gives many owners on one thread: Rc::clone(&data) adds to the owner count, Rc::strong_count(&data) reads it (1, 2, 3), and the data is thrown away when the last owner is done. Its contents can only be read. RefCell<T> moves the borrow rules to run time: borrow() borrows to read, borrow_mut() to write, and breaking the rules panics with RefCell already borrowed. Rc<RefCell<T>> is for shared data that changes. Weak (a pointer that isn't counted as an owner) breaks the cycle of two Rcs that point at each other. For many threads: Arc<T> (Rc for many threads) and Arc<Mutex<T>> (Mutex: a lock that makes other threads wait).
⚡ Box: a locker on the heap
Write:
enum Stack {
Slip(u32, Box<Stack>),
Empty,
}
Meaning: Stack is a stack of slips: each Slip holds a price (u32) and the rest of the stack below it. Box<T> puts data on the heap with one owner, like a locker in the storeroom whose key you hold, and its pointer is only 8 bytes. Without the Box, Stack holds a Stack again with no end: this recursive type (a type that contains itself) has infinite size, so it is refused (E0072).
⚡ Rc: many owners, one piece of data
Write:
let menu = Rc::new(Menu { name: String::from("Menu board") });
let cashier1 = Rc::clone(&menu);
println!("owners: {}", Rc::strong_count(&menu)); // 2
Meaning: Rc (reference counted) gives one piece of data, here the menu board, many owners, and counts them. Rc::clone doesn't copy the board, it only adds to the owner count. Rc::strong_count reads that count: menu and cashier1, so 2. The data is thrown away when the last owner is done. It suits a graph node (a point joined by lines) held by many edges (lines) on one thread.
⚡ RefCell: checked while running
Guess first: egg_stock is a number inside a RefCell, and borrow_mut() borrows it to change it. cashier1 still holds a borrow_mut(), then cashier2 asks for a borrow_mut() too. Does it compile?
It does, then it panics while the program runs: RefCell already borrowed. The compiler can't see inside a RefCell, so the rules (many readers, or one writer) are only checked while the program runs.
Meaning: RefCell<T> lets its contents change through a plain borrow (&, not &mut). Keep the borrow as short as you can: *egg_stock.borrow_mut() -= 2; on one line.