Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Smart Pointers and Memory

Rust Rc<T> type

Reference for Rust Rc<T>: shared ownership on a single thread, strong and weak counts, Rc::clone, get_mut, make_mut, try_unwrap and ptr_eq.

Rc<T> ("reference counted") is a smart pointer that gives several owners shared, read-only access to one value on the heap. Cloning an Rc does not copy the value: it copies the pointer and adds one to a counter. When the last Rc is dropped, the counter reaches zero and the value is dropped too.

Rc is not thread-safe. Its counter uses plain integer arithmetic, so the compiler marks Rc<T> as neither Send nor Sync. Use Arc<T> when the value must cross threads. Because the contents are shared, Rc<T> only hands out &T; to mutate shared data, combine it with RefCell<T> or Cell<T>.

Rust
use std::rc::Rc;

let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a);   // cheap: bumps the strong count

Try it

Rust Counting owners

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.

Rust Shared mutation with RefCell, and make_mut

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.

Syntax

Rust
pub struct Rc<T: ?Sized, A: Allocator = Global> { /* private */ }

impl<T> Rc<T> {
    pub fn new(value: T) -> Rc<T>;
    pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
        where F: FnOnce(&Weak<T>) -> T;
    pub fn try_unwrap(this: Rc<T>) -> Result<T, Rc<T>>;
    pub fn into_inner(this: Rc<T>) -> Option<T>;
}

impl<T: ?Sized> Rc<T> {
    pub fn strong_count(this: &Rc<T>) -> usize;
    pub fn weak_count(this: &Rc<T>) -> usize;
    pub fn downgrade(this: &Rc<T>) -> Weak<T>;
    pub fn get_mut(this: &mut Rc<T>) -> Option<&mut T>;
    pub fn ptr_eq(this: &Rc<T>, other: &Rc<T>) -> bool;
}

impl<T: Clone> Rc<T> {
    pub fn make_mut(this: &mut Rc<T>) -> &mut T;
    pub fn unwrap_or_clone(this: Rc<T>) -> T;
}
Method Description
Rc::new(v) Moves v to the heap with strong count 1.
Rc::clone(&rc) Returns another owner and increments the strong count.
Rc::strong_count / weak_count Number of Rc / Weak pointers to the value.
Rc::downgrade(&rc) Creates a non-owning Weak<T>.
Rc::get_mut(&mut rc) Some(&mut T) only if there are no other Rc or Weak pointers.
Rc::make_mut(&mut rc) Gives &mut T, cloning the value first if it is shared.
Rc::try_unwrap(rc) Returns the value if this is the only strong owner, otherwise gives the Rc back in Err.
Rc::ptr_eq(&a, &b) Compares allocation addresses, not values.

Errors / panics / edge cases. These are associated functions, not methods (Rc::strong_count(&a), not a.strong_count()), so they never collide with methods of T reached through auto-deref. Counter overflow aborts the process, which cannot happen in practice. Rc::new_cyclic lets a value hold a Weak to itself; upgrading that Weak inside the closure always fails because the value is not built yet.

Usage notes

  • Rc::clone(&a) is preferred over a.clone() by convention: it signals a cheap count bump rather than a deep copy.
  • Rc<T> compares, hashes and formats like T (==, Hash, Display and Debug delegate to the inner value). Use Rc::ptr_eq for identity.
  • Reference cycles (a owns b, b owns a) are never freed, because the counts never reach zero. Break cycles with Weak<T>; see Weak.
  • Rc<str> and Rc<[T]> are cheap-to-clone immutable strings and slices (Rc::from("text")); they avoid the extra pointer hop of Rc<String>.
  • Cloning costs one non-atomic increment, noticeably cheaper than Arc. Pick Rc for single-threaded graphs, trees with shared subtrees and observer lists.
  • Rc<RefCell<T>> moves borrow checking to run time: a conflicting borrow_mut panics.
  • Rc::try_unwrap fails while any other strong owner exists; Weak pointers do not block it.