Bitpath

Lesson 2 · Unit 04

Smart pointers

Box, Rc and RefCell, and what each one relaxes

13 exercisesabout 3 min

What you practise

  • Box for the heap, Rc for shared ownership, RefCell for 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?

Rust
enum List {
    Cons(i32, List),
    Nil,
}

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.

Rust
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.

Rust
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.

Rust
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.

One email when Bitpath is ready to try. Nothing else. Privacy