You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-27 03:01:03 +02:00
1.4 KiB
1.4 KiB
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 = Rc::clone(&a);
println!("a: {a}");
println!("b: {b}");
}
- See
Arc
andMutex
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.
Rc
's count ensures that its contained value is valid for as long as there are references.Rc
in Rust is likestd::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 withRefCell
, on the next slide).