Box, Rc and RefCell
Box puts a value on the heap. Rc shares ownership with reference counting and RefCell allows mutation checked at runtime. Rc<RefCell<T>> is the common shared mutable pattern.
Example
use std::rc::Rc;
use std::cell::RefCell;
let shared = Rc::new(RefCell::new(vec![1]));
let other = Rc::clone(&shared);
other.borrow_mut().push(2);
println!("{:?} {}", shared.borrow(), Rc::strong_count(&shared));Result
[1, 2] 2
Exercise
Share ownership.
::new(5)Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.