Rc
Rc is a reference-counted shared pointer. Use this when you need to refer
to the same data from multiple places:
use std::rc::Rc; fn main() { let mut a = Rc::new(10); let mut b = a.clone(); println!("a: {a}"); println!("b: {b}"); }
Shared references in Rust disallow mutation by default.
If you need to mutate the data inside an Rc, you will need to wrap the data in
a type such as Cell or RefCell, in single-threaded cases. See Arc if you are in a multi-threaded
context. Arc stands for “Atomically Reference counted”. If you need to mutate through Arc use Mutex, RwLock, or one of the Atomic types.
- Like C++’s
std::shared_ptr. cloneis cheap: creates a pointer to the same allocation and increases the reference count.make_mutactually clones the inner value if necessary (“clone-on-write”) and returns a mutable reference.