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
Replay: real traced execution (multi-file project)
use std::rc::Rc;
fn main() {
let label = "cache";
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 = "config";
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 = "session";
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);
}
label ← "cache", shared ← "cache", first ← "cache", second ← "cache"
3fn main() {4 let labe→ "cache"l = "cache"; //@label="cache", "config", "session"5 let share→ "cache"d = Rc::new(String::from(labe"cache"l));6 let firs→ "cache"t = Rc::clone(&share"cache"d);7 let secon→ "cache"d = Rc::clone(&share"cache"d);8 let coun→ 3t = Rc::strong_count(&share"cache"d);9 println!("{} {count}", first);10}outputcache 3
label ← "config", shared ← "config", first ← "config", second ← "config"
3fn main() {4 let labe→ "config"l = "config";5 let share→ "config"d = Rc::new(String::from(labe"config"l));6 let firs→ "config"t = Rc::clone(&share"config"d);7 let secon→ "config"d = Rc::clone(&share"config"d);8 let coun→ 3t = Rc::strong_count(&share"config"d);9 println!("{} {count}", first);10}outputconfig 3
label ← "session", shared ← "session", first ← "session", second ← "session"
3fn main() {4 let labe→ "session"l = "session";5 let share→ "session"d = Rc::new(String::from(labe"session"l));6 let firs→ "session"t = Rc::clone(&share"session"d);7 let secon→ "session"d = Rc::clone(&share"session"d);8 let coun→ 3t = Rc::strong_count(&share"session"d);9 println!("{} {count}", first);10}outputsession 3
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.