Skip to content
Theory · Smart pointers · lesson 3 of 6

Rc and the reference count

In the previous lesson the key to a locker had exactly one holder. Now picture a library book that several people read at once. Its card records how many readers the book has.

A new reader comes — the number on the card goes up. A reader returns the book — the number goes down. When the card shows zero, the book is taken back to storage.

In Rust a value has one owner. Let's try to give one book to two readers:

Rust
fn main() {
    let book = String::from("Rust");
    let anna = book;
    let boris = book; // ✗
    println!("{anna} {boris}");
}
TEXT
error[E0382]: use of moved value: `book`

The program does not compile: the string moved to anna, and boris can no longer get it. clone would give boris his own copy, but then there would be two books. And references would require proving with lifetimes which reader lives longer — sometimes nobody knows that.

Several owners of one value

Rc<T> is a smart pointer that lets a value have several owners. The value lives on the heap, and next to it sits a reference count: the number of owners the value has right now.

Rust
use std::rc::Rc;

fn main() {
    let book = Rc::new(String::from("Rust"));
    let anna = Rc::clone(&book);
    let boris = Rc::clone(&book);
    println!("{anna} {boris}"); // Rust Rust
    println!("{}", Rc::strong_count(&book)); // 3
}

Let's walk through the example line by line:

  1. use std::rc::Rc; makes the name Rc from the standard library available: without this line the compiler does not know the name Rc.
  2. Rc::new(...) puts the string on the heap next to a count of 1: so far there is one owner — book.
  3. Rc::clone(&book) does not copy the string. It hands out one more pointer to the same string and increments the count: anna is the second owner.
  4. The second Rc::clone makes boris an owner, and the count becomes 3.
  5. println! prints Rust Rust: both owners read the very same string.
  6. Rc::strong_count(&book) reads the count and prints 3.

book.clone() does the same thing, but the convention is to write Rc::clone(&book). That way a reader of the code sees a cheap count increment at once, not a copy of the whole string.

A reader on the card here is a co-owner of the Rc, not a & reference from the borrowing theme. The reference &book by itself does not change the count; Rc::clone does.

The count goes up and down

The count changes by four rules:

  • Rc::new starts the count at 1;
  • each Rc::clone adds 1;
  • each owner that goes out of scope takes 1 off — the Drop code of Rc does that;
  • when the count reaches zero, the value is freed.

Step through the program and watch the note next to main: it holds the count. Pay attention to the step where the inner block ends.

LiveThe Rc countstep 1 of 11 · frames: 1

Rc::new puts the string on the heap next to the count; there is one owner.

Watch the count in the note next to main

So, step by step through the trace:

  1. Each Rc::clone added 1 to the count, and the heap still held one string.
  2. At the closing brace of the block, c was dropped and took 1 off.
  3. drop(b) took off another 1 before the end of main.
  4. The string was freed only when the last owner left.

Interviewers often ask how Rc knows when to free the value. The answer is the count: each owner decrements it when dropped, and the one that brings it to zero frees the value.

A name with an underscore

Sometimes an owner is needed only for the count, and nobody will read it. To keep the compiler from warning about an unused variable, the name starts with an underscore: _b. Such a variable lives like any other — until the end of its scope.

A bare _ is a different matter: it is not a name. A new value sent into _, such as the result of Rc::clone(&a), is dropped right away. But let _ = b; with an existing variable does nothing: b stays alive.

Rust
use std::rc::Rc;

fn main() {
    let a = Rc::new(5);
    let _b = Rc::clone(&a);
    let _ = Rc::clone(&a);
    println!("{}", Rc::strong_count(&a)); // 2
}

Let's go step by step:

  1. a is the first owner, and the count is 1.
  2. _b is the second owner, and it lives until the end of main: the count is 2.
  3. let _ = Rc::clone(&a); creates a clone and drops it at once: the count briefly became 3 and went back to 2.
  4. It prints 2.

Common mistake

Here the library picture breaks. A reader of a real book can make notes in it, but an owner of an Rc cannot. Beginners try to append something to the shared string:

Rust
use std::rc::Rc;

fn main() {
    let book = Rc::new(String::from("Rust"));
    let anna = Rc::clone(&book);
    anna.push_str("!"); // ✗
    println!("{book}");
}
TEXT
error[E0596]: cannot borrow data in an `Rc` as mutable

The program does not compile. Rc hands out only a shared reference &T. If two owners could change the value at the same time, the "one mutable reference" rule would stop working. You can still change a shared value, but one Rc is not enough for that: the borrowing rules have to be checked while the program runs.

Key points

  • Rc<T> gives a value several owners: Rc::new starts the count at 1, and Rc::clone(&a) adds an owner without copying.
  • An owner that goes out of scope takes 1 off, and at zero the value is freed.
  • _b lives until the end of its scope, while a new value in a bare _ is dropped right away.
  • Rc gives read access only: you cannot change the value through it (E0596).