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>.
use std::rc::Rc; let a = Rc::new(String::from("shared")); let b = Rc::clone(&a); // cheap: bumps the strong count
Try it
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.
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
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 overa.clone()by convention: it signals a cheap count bump rather than a deep copy.Rc<T>compares, hashes and formats likeT(==,Hash,DisplayandDebugdelegate to the inner value). UseRc::ptr_eqfor identity.- Reference cycles (
aownsb,bownsa) are never freed, because the counts never reach zero. Break cycles withWeak<T>; see Weak. Rc<str>andRc<[T]>are cheap-to-clone immutable strings and slices (Rc::from("text")); they avoid the extra pointer hop ofRc<String>.- Cloning costs one non-atomic increment, noticeably cheaper than
Arc. PickRcfor single-threaded graphs, trees with shared subtrees and observer lists. Rc<RefCell<T>>moves borrow checking to run time: a conflictingborrow_mutpanics.Rc::try_unwrapfails while any other strong owner exists;Weakpointers do not block it.
Related
- Weak, Arc, RefCell, Cell, Cow
- Tutorial: Rc and Arc, Smart pointers overview, RefCell and Cell