============
:rust:`Rc`
============

------------
:rust:`Rc`
------------

:url:`Rc <https://doc.rust-lang.org/std/rc/struct.Rc.html>` is a
reference-counted shared pointer. Use this when you need to refer to the
same data from multiple places:

.. code:: rust

   use std::rc::Rc;

   fn main() {
       let a = Rc::new(10);
       let b = Rc::clone(&a);

       println!("a: {a}");
       println!("b: {b}");
   }

-  See :url:`Arc <../concurrency/shared-state/arc.md>` and
   :url:`Mutex <https://doc.rust-lang.org/std/sync/struct.Mutex.html>`
   if you are in a multi-threaded context.
-  You can *downgrade* a shared pointer into a
   :url:`Weak <https://doc.rust-lang.org/std/rc/struct.Weak.html>`
   pointer to create cycles that will get dropped.

---------
Details
---------

-  :rust:`Rc` count ensures that its contained value is valid for as
   long as there are references.
-  :rust:`Rc` in Rust is like :rust:`std::shared_ptr` in C++.
-  :rust:`Rc::clone` is cheap: it creates a pointer to the same allocation
   and increases the reference count. Does not make a deep clone and can
   generally be ignored when looking for performance issues in code.
-  :rust:`make_mut` actually clones the inner value if necessary
   ("clone-on-write") and returns a mutable reference.
-  Use :rust:`Rc::strong_count` to check the reference count.
-  :rust:`Rc::downgrade` gives you a *weakly reference-counted* object to
   create cycles that will be dropped properly (likely in combination
   with :rust:`RefCell`).
