RefCell and interior mutability in Rust
RefCell moves the borrow check to run time, so a shared value can still be mutated.
use std::cell::RefCell;
struct Log {
entries: RefCell<Vec<String>>,
}
impl Log {
fn record(&self, line: &str) {
self.entries.borrow_mut().push(line.to_string());
}
fn count(&self) -> usize {
self.entries.borrow().len()
}
}
fn main() {
let log = Log { entries: RefCell::new(Vec::new()) };
log.record("started");
log.record("finished");
println!("{} entries", log.count());
println!("{:?}", log.entries.borrow());
}
How it works
borrow_mutpanics if a borrow is already outstanding.- The value itself needs no
mutbinding. - Keep the borrows short to keep the panics away.
Keywords and builtins used here
LogRefCellStringVeccountfnimplletmainrecordselfstrstructuseusize
The run, in numbers
- Lines
- 23
- Characters to type
- 417
- Tokens
- 147
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 80 seconds.
Step 1 of 3 in Interior mutability, step 7 of 11 in Lifetimes & interior mutability.