WeCodeAcademy

Rust Box, Rc and RefCell

A Box<T> puts a value on the heap. Rc<T> lets several owners share a value. RefCell<T> allows changing data behind a shared reference, checked at run time.

ExampleRust
use std::cell::RefCell;
use std::rc::Rc;

enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn sum(list: &List) -> i32 {
    match list {
        List::Cons(v, rest) => v + sum(rest),
        List::Nil => 0,
    }
}

fn main() {
    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil))))));
    println!("{}", sum(&list));

    let shared = Rc::new(RefCell::new(vec![1, 2]));
    let a = Rc::clone(&shared);
    let b = Rc::clone(&shared);
    a.borrow_mut().push(3);
    b.borrow_mut().push(4);
    println!("{:?} owners={}", shared.borrow(), Rc::strong_count(&shared));
}
Output
6
[1, 2, 3, 4] owners=3
Quick check

Which type lets several owners share one value?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.