ownership

Rust Interior mutability

An API may permit a carefully controlled change through a shared reference. For example, a counter can record calls without demanding exclusive access to an entire service. Safe cell abstractions enforce the necessary restrictions; this is not permission to create overlapping mutable references. Expected output (not executed): 2 Why: The counter changes through the shared receiver using Cell operations. Common mistake: Adding interior mutability to every field instead of using ordinary &mut self where possible.

Formal Syntax & Structure

rust syntaxrust
fn update(&self)

Working Example

Example Snippetrust
use std::cell::Cell;struct Meter { calls: Cell<u32> }impl Meter {    fn record(&self) { self.calls.set(self.calls.get() + 1); }}fn main() {    let meter = Meter { calls: Cell::new(0) };    meter.record(); meter.record();    println!("{}", meter.calls.get());}
Rust Reference