Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 132 ยท Smart Pointers and Memory

Rc, Arc and Shared Ownership

Learn Rust Rc<T> and Arc<T> for shared ownership: strong_count, clone cost, Rc<RefCell<T>>, Weak pointers, parent links in trees, reference cycles and threads.

Rust's ownership rule says every value has exactly one owner. That rule is wonderful for correctness, and it handles most programs. But some data really does have several owners: a node in a graph that two other nodes point at, a configuration object read by many parts of a program, a cached image used by several widgets. Who frees the data when nobody knows which user is the last one?

The answer is reference counting. Rc<T> (single-threaded) and Arc<T> (thread-safe) keep a counter next to the value. Each owner holds a handle; cloning a handle bumps the counter, dropping a handle lowers it, and when it reaches zero the value is dropped. Still no garbage collector, no manual free: the counter is the owner of the cleanup. This lesson builds from the basics to the interesting traps (cycles) and the pointer that fixes them (Weak).

If Box is new to you, read Box and the Heap first. The next lesson, Interior Mutability: Cell and RefCell, explains how to mutate shared data.

Rc: shared ownership on one thread

Rc::new(value) moves the value to the heap and returns the first handle. Rc::clone(&handle) makes another handle to the same value; it does not copy the value.

Rust Rc handles and strong_count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The counter goes 1, 2, 3, back to 2, then 1. Methods of the inner String (len, and Display) are reachable through the handle because Rc<T> implements Deref<Target = T>.

Rc::clone versus .clone()

a.clone() on an Rc does the same thing as Rc::clone(&a). Rust style prefers writing Rc::clone(&a) because it announces "this is a cheap handle copy, not a deep copy". Cloning an Rc is one non-atomic increment; cloning the String inside would allocate and copy bytes. Reading code that clones in a loop is much easier when the cheap clones are visibly cheap.

Rust Sharing a list tail

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two lists share one tail in memory. With Box<List> this is impossible, because a Box has a single owner. This "persistent data structure" trick is one of the original reasons for Rc in functional-style code.

Rc gives you shared, immutable access

An Rc<T> hands out only &T. Many owners with mutation would break the aliasing rule (many readers or one writer), so Rust refuses:

Rust Mutating through an Rc (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc stops with error E0596, "cannot borrow data in an Rc as mutable", plus the help that the trait DerefMut is required to modify through a dereference but is not implemented for Rc<Vec<i32>>. That is the compiler enforcing the rule for you.

There are three ways forward, each with a different meaning:

  1. Clone-on-write: Rc::make_mut(&mut rc) gives &mut T. If other handles exist, it first clones the data so you get your own private copy.
  2. Exclusive access: Rc::get_mut(&mut rc) returns Some(&mut T) only when the count is exactly 1.
  3. Interior mutability: put a RefCell or Cell inside, as in the next lesson: Rc<RefCell<T>>.
Rust make_mut, get_mut and try_unwrap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

After make_mut, a has its own copy [1, 2, 3, 4, 5] while b keeps [1, 2, 3, 4]. Because a was the only handle to its new copy, try_unwrap succeeds. Rc::ptr_eq compares addresses (are they the same allocation?), not contents.

Rc<RefCell>: shared and mutable

The standard recipe for "many owners, anyone may change the value" on one thread is Rc<RefCell<T>>. RefCell checks borrowing rules at runtime instead of compile time; the details are in the RefCell lesson. Here is the shape:

Rust A shared counter with Rc and RefCell

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two buttons, one counter. This is the shape of observer lists, shared caches and graph nodes in single-threaded Rust.

Reference cycles and Weak

Reference counting has one famous weakness: if two values point at each other with strong handles, neither count ever reaches zero. The memory is leaked. Rust considers that memory-safe (nothing dangling), but it is still a bug. Weak<T> solves it. A Weak handle does not keep the value alive; you must call upgrade() to try to get an Rc back, and you get None if the value is already gone.

Rust A cycle that never frees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each node is referenced by its own variable and by the other node, so every count is 2. When main ends the variables release one reference each, leaving 1, never 0. The Drop messages never appear: the memory leaks until the process exits.

Fix it by making one direction weak. A weak handle comes from Rc::downgrade(&rc). The classic use is a tree with parent pointers: parents own children strongly, children point at the parent weakly.

Rust A tree with parent pointers using Weak

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Walk through it: root owns docs strongly (docs has strong count 2: the variable and the children vector) and docs points back with a weak handle (root has weak count 1). When we drop the variable root, its strong count goes from 1 to 0, so the root node is destroyed ("dropping root" is printed) and so is its children list, which releases one of docs' handles. After that docs.parent.upgrade() returns None. No leaks, no dangling parent. The rest of the nodes are freed when main ends.

Rule of thumb for graphs: owning edges are strong, back edges are weak. Parent-to-child strong, child-to-parent weak; observable-to-observer strong, observer-to-subject weak.

Arc: reference counting across threads

Rc uses plain, non-atomic increments, which is fast but unsafe if two threads touch the counter at once. The compiler knows: Rc<T> does not implement the Send trait, so you cannot move it to another thread.

Rust Rc cannot cross threads (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is E0277, "Rc<Vec<i32>> cannot be sent between threads safely", with a note that the trait Send is not implemented for Rc<Vec<i32>>. The fix is Arc<T> ("atomically reference counted"). It has the same API (Arc::new, Arc::clone, Arc::strong_count, Arc::downgrade) but the counter uses atomic instructions, a little slower per clone, and safe from any thread.

Rust Arc shared between threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

We collect the results in spawn order so the output is deterministic; the threads themselves may run in any order. After join, the thread closures (and their Arc clones) are gone, so the count is back to 1.

Like Rc, Arc<T> gives only shared access. To mutate across threads you wrap the data in a lock: Arc<Mutex<T>>. That is the topic of the concurrency chapter, but here is a preview:

Rust Arc with Mutex preview

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Four threads, 1000 increments each, always 4000: the mutex makes each increment exclusive.

Performance and design notes

  • Clone cost: Rc::clone is a non-atomic add (about a nanosecond); Arc::clone is an atomic add, which is slower especially under contention from many cores. Both are far cheaper than deep copies.
  • Memory: an Rc<T> allocation holds two counters (strong and weak, one machine word each) plus T, and the handle is one pointer. Rc<str> and Rc<[T]> exist for immutable shared strings and slices.
  • Prefer borrowing when you can. Passing &T costs nothing. Reach for Rc/Arc only when ownership truly cannot be expressed by a single owner plus references (graphs, caches, callbacks, shared state in threads).
  • Don't use Arc on one thread "just in case", and don't use Rc with threads; the compiler will tell you anyway.
  • Cycles leak. Use Weak for back edges, or restructure around indexes into a Vec (an arena), which avoids reference counting completely.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Rc::clone(&a) do?

    Cloning an Rc is cheap: it only bumps the counter. All handles point to the same allocation.
  2. 2. Why does numbers.push(4) fail when numbers: Rc<Vec<i32>>?

    Rc<T> implements Deref but not DerefMut. Use Rc::make_mut, Rc::get_mut or put a RefCell inside.
  3. 3. Two values hold strong Rc handles to each other. What happens when both variables go out of scope?

    A cycle keeps each count at 1 forever. Rust considers leaks memory-safe, so it compiles. Use Weak for one direction.
  4. 4. What does weak.upgrade() return?

    A Weak does not keep the value alive. upgrade() gives Some(Rc) while strong owners exist, otherwise None.
  5. 5. When should you choose Arc over Rc?

    Arc uses atomic counters and is Send/Sync when T is. Rc is not Send, and its cheaper counter is only safe on one thread.

Summary

  • Rc<T> gives single-threaded shared ownership; the value is dropped when the last strong handle goes away. Rc::clone copies the handle, not the data.
  • Rc hands out only shared access. Use Rc::make_mut (clone on write), Rc::get_mut (when unique) or Rc<RefCell<T>> for mutation.
  • Rc::strong_count, Rc::weak_count, Rc::ptr_eq and Rc::try_unwrap inspect and unwrap handles.
  • Strong cycles leak. Make back edges Weak<T> (Rc::downgrade) and call upgrade() to use them.
  • Arc<T> is the thread-safe version with atomic counters; combine it with Mutex or RwLock to mutate.
  • Prefer plain borrowing; use reference counting when ownership is truly shared.

Next: Interior Mutability: Cell and RefCell