Interior Mutability Concepts
Rc and RefCell
Shared Mutable State
Rc<RefCell<T>> combines shared ownership with checked interior mutation in single-threaded code.
Program
Play the program to choose an increment, clone a shared owner, and update the value through the clone.
shared_refcell.rs
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let delta = ;
let shared = Rc::new(RefCell::new(10));
let owner = Rc::clone(&shared);
*owner.borrow_mut() += delta;
let value = *shared.borrow();
println!("{value}");
}
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let delta = ;
let shared = Rc::new(RefCell::new(10));
let owner = Rc::clone(&shared);
*owner.borrow_mut() += delta;
let value = *shared.borrow();
println!("{value}");
}
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let delta = ;
let shared = Rc::new(RefCell::new(10));
let owner = Rc::clone(&shared);
*owner.borrow_mut() += delta;
let value = *shared.borrow();
println!("{value}");
}
Rc<RefCell<T>>
`Rc` shares ownership, while `RefCell` allows checked mutation of the inner value.
clone handle
`Rc::clone` creates another owner of the same allocation.
mutable borrow
`borrow_mut` temporarily opens the inner value for mutation.