Mutate Fields Behind &self With Cell And RefCell

Combine Cell for Copy counters and RefCell for heap buffers so an immutable &self handle can record metrics and events safely at runtime.

RustResilience

Code

snippet
use std::cell::{Cell, RefCell};

struct RequestTracker {
    hits: Cell<u32>,
    events: RefCell<Vec<String>>,
}

impl RequestTracker {
    fn new() -> Self {
        Self {
            hits: Cell::new(0),
            events: RefCell::new(Vec::new()),
        }
    }

    fn record(&self, route: &str) {
        self.hits.set(self.hits.get() + 1);
        self.events.borrow_mut().push(route.to_string());
    }

    fn summary(&self) -> (u32, usize) {
        (self.hits.get(), self.events.borrow().len())
    }
}

fn main() {
    let tracker = RequestTracker::new();
    tracker.record("/health");
    tracker.record("/orders");
    tracker.record("/metrics");

    let (count, len) = tracker.summary();
    println!("hits={count}, recorded={len}");
    println!("events={:?}", tracker.events.borrow());
}

Inside the implementation — Mutate Fields Behind &self With Cell And RefCell

Computational mechanics sit within the helpers new, record, summary and main — everything else is wiring.

Points of care

  • No dependency manager needed; native runtime APIs back every single operation.

Applying it

Signature: fn new() -> Self

Expect labeled output — hits=, events= — when the file runs.

Running the file executes main, which drives new, record and summary in order.

Statements that matter

fn summary(&self) -> (u32, usize) {
    (self.hits.get(), self.events.borrow().len())
}
fn record(&self, route: &str) {
    self.hits.set(self.hits.get() + 1);
    self.events.borrow_mut().push(route.to_string());
}
fn new() -> Self {
    Self {
        hits: Cell::new(0),
        events: RefCell::new(Vec::new()),
    }
}

Interactive Tools for This Topic

FAQ

What does Mutate Fields Behind &self With Cell And RefCell print when run?
Running the file directly is enough — expect labeled output lines such as `hits=`, `events=`.