Borrow checker Advanced

28  Interior mutability

Sometimes a value must change behind a shared reference -- a counter, a cache, a shared log. Cell and RefCell move the borrow rules to runtime; Rc<RefCell<..>> is the classic shared-mutable combo.

Step 2 / 2

Implement new_log and write: two handles, one shared, mutable log.

Hints
  • One allocation, two handles: make the Rc once, then Rc::clone it.
  • log.borrow_mut().push(msg.to_string()) -- the mutable borrow lives only for that line.
28_interior_mut.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
use std::cell::RefCell;
use std::rc::Rc;

type Log = Rc<RefCell<Vec<String>>>;

fn new_log() -> (Log, Log) {
    let log = Rc::new(RefCell::new(Vec::new()));
    (Rc::clone(&log), log)
}

fn write(log: &Log, msg: &str) {
    log.borrow_mut().push(msg.to_string());
}