Rc<RefCell<T>> in Rust
Shared ownership plus interior mutability: several handles onto one mutable value.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(vec!["basics".to_string()]));
let editor = Rc::clone(&shared);
editor.borrow_mut().push("traits".to_string());
let viewer = Rc::clone(&shared);
println!("{:?}", viewer.borrow());
println!("owners: {}", Rc::strong_count(&shared));
shared.borrow_mut().retain(|t| t != "basics");
println!("{:?}", editor.borrow());
}
How it works
Rccounts owners;RefCellallows the mutation.- Every clone sees the same underlying value.
- This combination is single-threaded only.
Keywords and builtins used here
fnletmainuse
The run, in numbers
- Lines
- 16
- Characters to type
- 404
- Tokens
- 143
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 78 seconds.
Step 2 of 3 in Interior mutability, step 8 of 11 in Lifetimes & interior mutability.