Back to Comprehensive Rust

`Rc`

src/smart-pointers/rc.md

latest2.0 KB
Original Source
<!-- Copyright 2023 Google LLC SPDX-License-Identifier: CC-BY-4.0 -->

Rc

Rc is a reference-counted shared pointer. Use this when you need to refer to the same data from multiple places:

rust,editable
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
use std::rc::Rc;

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

    dbg!(a);
    dbg!(b);
}

Each Rc points to the same shared data structure, containing strong and weak pointers and the value:

bob
 Stack                     Heap
.- - - - - - - -.     .- - - - - - - - - - - - - - - - -.
:               :     :                                 :
:     +-----+   :     :   +-----------+-------------+   :
:  a: | o---|---:--+--:-->|  count: 2 |  value: 10  |   :
:     +-----+   :  |  :   +-----------+-------------+   :
:  b: | o---|---:--+  :                                 :
:     +-----+   :     `- - - - - - - - - - - - - - - - -'
:               :     
`- - - - - - - -'
  • See Arc and Mutex if you are in a multi-threaded context.
  • You can downgrade a shared pointer into a Weak pointer to create cycles that will get dropped.
<details>
  • Rc's count ensures that its contained value is valid for as long as there are references.
  • Rc in Rust is like std::shared_ptr in C++.
  • 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.
  • make_mut actually clones the inner value if necessary ("clone-on-write") and returns a mutable reference.
  • Use Rc::strong_count to check the reference count.
  • Rc::downgrade gives you a weakly reference-counted object to create cycles that will be dropped properly (likely in combination with RefCell).
</details>