typestar

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

  1. borrow_mut panics if a borrow is already outstanding.
  2. The value itself needs no mut binding.
  3. Keep the borrows short to keep the panics away.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Interior mutability, step 7 of 11 in Lifetimes & interior mutability.

← Previous Next →