Lesson 2 · Unit 04
Smart pointers
Box, Rc and RefCell, and what each one relaxes
What you practise
Boxfor the heap,Rcfor shared ownership,RefCellfor checked mutation, a tree that needs them
Try a question from this lesson
Pick one
A linked list: each Cons holds a number and the list that follows. The compiler must know the size of every type. Why does it reject this one?
enum List {
Cons(i32, List),
Nil,
}Correct answer
A List holds a List: its size has no end
Why
A value is stored inline, so a List would contain a List that contains a List: "recursive type List has infinite size". The compiler suggests indirection: store a pointer, which has a fixed size.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Box: a value on the heap
Box<T> owns a value stored on the heap. The box itself is only a pointer, so its size is known whatever it points to. That is what makes recursive types possible.
It follows the usual rules: one owner, moved on assignment, and the heap value is freed when the box is dropped. In Python every object already lives behind such a pointer.
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
let tail = Cons(2, Box::new(Nil));
let list = Cons(1, Box::new(tail));Concept
Rc: several owners
Sometimes one value needs several owners, like a node that two lists share. Rc<T>, reference counted, allows it.
Rc::clone(&a) copies no data. It makes another pointer to the same value and adds 1 to a counter. The value is dropped when the last Rc goes. Python manages every object this way. In Rust you opt in, and the shared value is read-only.
use std::rc::Rc;
let a = Rc::new(String::from("hi"));
let b = Rc::clone(&a);
println!("{b} {}", Rc::strong_count(&a));Concept
RefCell: rules checked at run time
RefCell<T> moves the borrow rules from compile time to run time. borrow() hands out a shared reference and borrow_mut() a mutable one, even through a plain &.
The cell counts them while the program runs and panics if a writer would overlap anyone else. Rc<RefCell<T>> is the usual pair: several owners and checked mutation.
use std::cell::RefCell;
let c = RefCell::new(5);
*c.borrow_mut() += 1;
println!("{}", c.borrow());9 more exercises in the app
- 1× fill the blanks
- 2× multiple choice
- 3× type the answer
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.