Sub topic 9
Rc<T>: several owners for one value
This chapter assumes you know ownership, moves, and borrowing. It also assumes you have seen Box<T>, Deref, and Drop from earlier chapters, and that you can read basic enums and traits.
The problem: one value, several owners
Ownership in Rust gives every value exactly one owner. Most of the time that is what you want. Some data structures break it. In a graph, several edges can point to the same node. In a shared configuration, several components may need to read the same value, and none of them is the obvious one to free it.
References do not solve this. A reference borrows from an owner, so the owner must outlive every borrower. If you cannot say which owner lives longest, you cannot pick the lifetimes.
Rc<T> solves it by counting. "Rc" stands for reference counted. An Rc<T> allocates a T on the heap together with a counter of how many Rc handles point at it. Cloning a handle adds one to the counter. Dropping a handle subtracts one. When the counter reaches zero, the value is dropped and its memory is freed.
Cloning a handle, not the data
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("shared"));
println!("count after creating a = {}", Rc::strong_count(&a));
let _b = Rc::clone(&a);
println!("count after creating b = {}", Rc::strong_count(&a));
{
let _c = Rc::clone(&a);
println!("count after creating c = {}", Rc::strong_count(&a));
}
println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}The program prints 1, 2, 3, and then 2. The string is allocated once. Rc::clone copies a pointer and increments the counter, so it is cheap no matter how large the data is. When _c leaves its block, its Drop implementation decrements the counter.
Rc::strong_count is an associated function, not a method. You write Rc::strong_count(&a), not a.strong_count(). The same holds for most Rc operations. This stops them from colliding with methods on T, which you reach through Deref.
Sharing a tail: a list with several heads
The cons list from the Box chapter cannot share nodes. If you build b from a with Box, a is moved and no longer usable. Replacing the Box with Rc fixes that:
use std::rc::Rc;
use List::{Cons, Nil};
enum List {
Cons(i32, Rc<List>),
Nil,
}
fn sum(list: &List) -> i32 {
match list {
Cons(value, rest) => value + sum(rest),
Nil => 0,
}
}
fn main() {
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
let b = Cons(3, Rc::clone(&a));
let c = Cons(4, Rc::clone(&a));
println!("a = {}, b = {}, c = {}", sum(&a), sum(&b), sum(&c));
println!("strong count of a = {}", Rc::strong_count(&a));
}This prints a = 15, b = 18, c = 19 and then strong count of a = 3. The a handle and the two clones inside b and c all own the same two-element tail. In sum(rest), rest has type &Rc<List>. Deref coercion turns it into &List, which is why the call compiles.
The count is 3 even though only a has a name. Each clone stored inside another value counts as an owner.
Rc::clone versus .clone()
a.clone() and Rc::clone(&a) do the same thing for an Rc. The community convention is to write Rc::clone(&a). When you skim code, x.clone() could be a deep copy of a large Vec, while Rc::clone(&x) tells the reader it only bumps a counter. Performance reviews are easier when the two look different.
Rc gives read-only access
Rc<T> hands out only shared references. It implements Deref<Target = T>, so you can read through it, but there is no DerefMut. Several owners with mutable access would break the aliasing rule, which allows either many readers or one writer.
use std::rc::Rc;
fn main() {
let a = Rc::new(vec![1, 2, 3]);
a.push(4); // error[E0596]: cannot borrow data in an `Rc` as mutable
}If you need mutation, you have three options:
- Use
Rc::get_mutorRc::make_mut, described below. - Put a
RefCell<T>inside theRc. A later chapter covers that combination. - Choose a design with a single owner.
Getting mutable access when it is safe
Two functions let you mutate through an Rc when no other owner can observe it.
Rc::get_mut(&mut rc) returns Some(&mut T) only when the strong count is 1 and there are no weak references. Otherwise it returns None.
Rc::make_mut(&mut rc) always returns &mut T. If the value is shared, it first clones the inner data into a fresh allocation, so your handle becomes the only owner of a private copy. This is called clone-on-write. It requires T: Clone.
use std::rc::Rc;
fn main() {
let mut data = Rc::new(vec![1, 2, 3]);
Rc::get_mut(&mut data).unwrap().push(4);
let other = Rc::clone(&data);
assert!(Rc::get_mut(&mut data).is_none());
Rc::make_mut(&mut data).push(5);
println!("data = {:?}", data);
println!("other = {:?}", other);
}The output is data = [1, 2, 3, 4, 5] and other = [1, 2, 3, 4]. After make_mut runs on a shared value, data and other no longer point to the same allocation.
Taking the value back out
When you hold the last handle, you can recover the inner value with Rc::try_unwrap. It returns Ok(T) if the strong count is 1 and Err(rc) otherwise, giving the handle back so you can retry. Rc::into_inner is similar but returns Option<T>, and it is safe to call on each of several handles because exactly one of them gets the value.
You can also ask whether two handles share an allocation with Rc::ptr_eq(&a, &b). This compares addresses, not contents. Using == on two Rc<T> values compares the inner values through PartialEq.
What the counter costs
- Each
Rcallocation stores two counters, strong and weak, next to the value. That is two extra words on the heap. - Each clone and each drop writes to the counter. This is a plain, non-atomic increment, which is why
Rcis cheap. Rcis not a garbage collector. It frees a value when the strong count reaches zero, and it cannot find unreachable cycles. A later chapter covers the cycle problem and howWeak<T>solves it.
Rc is single-threaded
Because the counter is not atomic, two threads updating it at once could corrupt it. Rust prevents this at compile time. Rc<T> does not implement Send or Sync, so you cannot move it into a spawned thread:
use std::rc::Rc;
use std::thread;
fn main() {
let a = Rc::new(5);
let handle = thread::spawn(move || {
println!("{}", a); // error[E0277]: `Rc<i32>` cannot be sent between threads safely
});
handle.join().unwrap();
}For threads, use Arc<T>, the atomically counted version. It has the same API but pays a small cost for atomic operations. Do not use Arc in single-threaded code just in case, because that cost buys you nothing there.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot borrow data in an Rc as mutable` | `Rc` has no `DerefMut` | Use `Rc::get_mut`, `Rc::make_mut`, or `RefCell` inside |
| `Rc<_>` cannot be sent between threads safely | `Rc` is not `Send` | Switch to `Arc` |
| Memory never freed | Cycle keeps strong count above zero | Use `Weak<T>` for back links |
| Surprise deep copy of a large value | Wrote `.clone()` on the inner value, not the handle | Clone the `Rc`, not the data it points to |
| `try_unwrap` returns `Err` | Another handle still exists | Drop the other handles first, or keep sharing |
Exercise
What does this program print, and why? use std::rc::Rc; fn main() { let a = Rc::new(10); let b = Rc::clone(&a); let c = Rc::clone(&b); drop(a); println!("{}", Rc::strongcount(&c)); println!("{}", Rc::tryunwrap(c).is_ok()); }
Show answer
It prints 2 and then false. The three handles a, b, and c share one allocation, so the count is 3. Calling drop(a) lowers it to 2, and b and c remain. tryunwrap(c) succeeds only if the count is 1, so it returns Err because b is still alive, and isok() gives false.