When we interact with an Rc type, the following changes happen to it internally:

  • When you take a new shared reference to Rc by calling Clone()Rc increments its internal reference count. Rc internally uses the Cell type for its reference counts
  • When the reference goes out of scope, it decrements it
  • When all shared references go out of scope, the refcount becomes zero. At this point, the last drop call on Rc does its deallocation

Using reference counted containers gives us more flexibility in the implementation: we can hand out copies of our value as if it were a new copy without having to keep exact track of when the references go out of scope. That doesn't mean that we can mutably alias the inner values.

Rc<T> is mostly used via ...

Get The Complete Rust Programming Reference Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.