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:
fn main() {
let book = String::from("Rust");
let anna = book;
let boris = book; // ✗
println!("{anna} {boris}");
}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.
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:
use std::rc::Rc;makes the nameRcfrom the standard library available: without this line the compiler does not know the nameRc.Rc::new(...)puts the string on the heap next to a count of 1: so far there is one owner —book.Rc::clone(&book)does not copy the string. It hands out one more pointer to the same string and increments the count:annais the second owner.- The second
Rc::clonemakesborisan owner, and the count becomes 3. println!printsRust Rust: both owners read the very same string.Rc::strong_count(&book)reads the count and prints3.
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::newstarts the count at 1;- each
Rc::cloneadds 1; - each owner that goes out of scope takes 1 off — the
Dropcode ofRcdoes 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.
1use std::rc::Rc;2 3fn main() {4 let a = Rc::new(String::from("book"));5 println!("{}", Rc::strong_count(&a));6 let b = Rc::clone(&a);7 println!("{}", Rc::strong_count(&a));8 {9 let c = Rc::clone(&a);10 let n = Rc::strong_count(&c);11 println!("{n}");12 }13 println!("{}", Rc::strong_count(&a));14 drop(b);15 println!("{}", Rc::strong_count(&a));16}
Rc::new puts the string on the heap next to the count; there is one owner.
So, step by step through the trace:
- Each
Rc::cloneadded 1 to the count, and the heap still held one string. - At the closing brace of the block,
cwas dropped and took 1 off. drop(b)took off another 1 before the end ofmain.- 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.
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:
ais the first owner, and the count is 1._bis the second owner, and it lives until the end ofmain: the count is 2.let _ = Rc::clone(&a);creates a clone and drops it at once: the count briefly became 3 and went back to 2.- 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:
use std::rc::Rc;
fn main() {
let book = Rc::new(String::from("Rust"));
let anna = Rc::clone(&book);
anna.push_str("!"); // ✗
println!("{book}");
}error[E0596]: cannot borrow data in an `Rc` as mutableThe 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::newstarts the count at 1, andRc::clone(&a)adds an owner without copying.- An owner that goes out of scope takes 1 off, and at zero the value is freed.
_blives until the end of its scope, while a new value in a bare_is dropped right away.Rcgives read access only: you cannot change the value through it (E0596).