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.
Fix Tracker so record can count through &self: store the hits in a Cell.
Hints
Cell<u32>allows get/set through&selffor Copy types.self.hits.set(self.hits.get() + 1); the getter becomesself.hits.get().
Reveal solution
use std::cell::Cell;
struct Tracker { hits: Cell<u32> }
impl Tracker {
fn record(&self) {
self.hits.set(self.hits.get() + 1);
}
fn hits(&self) -> u32 {
self.hits.get()
}
}