Rc
Rc is a reference-counted shared pointer. Use this when you need to refer to the same data from multiple places:
1. ```
use std::rc::Rc;
```
3. ```
fn main() {
```
4. ```
let a = Rc::new(10);
```
5. ```
let b = Rc::clone(&a);
```
7. ```
println!("a: {a}");
```
8. ```
println!("b: {b}");
```
9. ```
}
```
- 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.
This slide should take about 5 minutes.
Rc‘s count ensures that its contained value is valid for as long as there are references.Rcin Rust is likestd::shared_ptrin C++.Rc::cloneis 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_mutactually clones the inner value if necessary (“clone-on-write”) and returns a mutable reference.- Use
Rc::strong_countto check the reference count. Rc::downgradegives you a weakly reference-counted object to create cycles that will be dropped properly (likely in combination withRefCell).
