Smart Pointers
Rc
Shared Read-Only Ownership
Rc<T> lets several owners point to the same immutable value in single-threaded code.
Program
Play the program to clone Rc handles and watch the shared owner count grow.
rc_shared_owner.rs
use std::rc::Rc;
fn main() {
let label = ;
let shared = Rc::new(String::from(label));
let first = Rc::clone(&shared);
let second = Rc::clone(&shared);
let count = Rc::strong_count(&shared);
println!("{} {count}", first);
}
use std::rc::Rc;
fn main() {
let label = ;
let shared = Rc::new(String::from(label));
let first = Rc::clone(&shared);
let second = Rc::clone(&shared);
let count = Rc::strong_count(&shared);
println!("{} {count}", first);
}
use std::rc::Rc;
fn main() {
let label = ;
let shared = Rc::new(String::from(label));
let first = Rc::clone(&shared);
let second = Rc::clone(&shared);
let count = Rc::strong_count(&shared);
println!("{} {count}", first);
}
Rc<T>
`Rc<T>` is a reference-counted smart pointer for shared ownership.
Rc::clone
`Rc::clone` creates another owner of the same allocation.
strong_count
`Rc::strong_count` reports how many owners currently exist.