Rc shared ownership in Rust
Reference counting for multiple owners of one value.
use std::rc::Rc;
fn main() {
let shared = Rc::new(vec![1, 2, 3]);
let a = Rc::clone(&shared);
let b = Rc::clone(&shared);
let count = Rc::strong_count(&shared);
let total: i32 = a.iter().sum();
println!("{count} {total} {}", b.len());
}
How it works
Rc::newwraps a value for sharing.Rc::clonebumps the count, not the data.strong_countreports how many owners exist.
Keywords and builtins used here
fni32letmainuse
The run, in numbers
- Lines
- 11
- Characters to type
- 238
- Tokens
- 91
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 55 seconds.
Step 2 of 2 in Smart pointers, step 14 of 15 in Ownership & borrowing.