Rust Tutorial · Smart Pointers and Concurrency · Lesson 23 of 29

Rust Smart Pointers: Box, Rc and RefCell

Put values on the heap with Box, share ownership with Rc, and mutate shared data with RefCell.

Create a free account to save this page, take notes and track your progress. Sign in

The common smart pointers

Type Use it for
Box<T> A value on the heap; recursive types; trait objects
Rc<T> Several owners in one thread (reference counted)
RefCell<T> Mutating through a shared reference, checked at runtime
Arc<T>, Mutex<T> The thread-safe equivalents (next page)
Box, Rc and RefCell
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug)]
enum Tree { Leaf(i32), Node(Box<Tree>, Box<Tree>) }

fn sum(tree: &Tree) -> i32 {
    match tree {
        Tree::Leaf(v) => *v,
        Tree::Node(l, r) => sum(l) + sum(r),
    }
}

fn main() {
    let tree = Tree::Node(Box::new(Tree::Leaf(2)), Box::new(Tree::Node(Box::new(Tree::Leaf(3)), Box::new(Tree::Leaf(5)))));
    println!("tree sum: {}", sum(&tree));

    let cart = Rc::new(RefCell::new(vec!["mug"]));
    let same_cart = Rc::clone(&cart);              // a second owner
    same_cart.borrow_mut().push("teapot");          // mutate through a shared handle
    println!("owners: {}, items: {:?}", Rc::strong_count(&cart), cart.borrow());
}

Output

tree sum: 10
owners: 2, items: ["mug", "teapot"]

Run this on your computer — see “Get Started” for setup.

Test yourself

What does Rc<T> give you?

  1. Thread-safe sharing
  2. Shared ownership of a value within one thread, freed when the last owner is dropped
  3. Heap allocation only
  4. A mutable reference
Show answer

Answer: Shared ownership of a value within one thread, freed when the last owner is dropped

Was this page helpful?