notes

Log | Files | Refs | README

interior_mutability.md (1316B)


      1 # Interior Mutability
      2 
      3 Interior mutability in Rust is a pattern that lets you change the internal state
      4 of a value through a shared (immutable) reference, something that normal
      5 borrowing rules do not allow.
      6 
      7 ## Core idea
      8 
      9 - Normally, &T means “shared, read-only” and &mut T means “unique, writable”.
     10 
     11 - A type has interior mutability if you can call methods that mutate its
     12   internal data even when you only have &self.
     13 
     14 - This is implemented by special wrapper types that enforce safety at runtime
     15   instead of purely at compile time (often via unsafe inside but a safe public
     16   API).
     17 
     18 ## Common types used
     19 
     20 - Rust’s standard library provides several types that rely on interior
     21   mutability:
     22 
     23 - Cell<T> and RefCell<T> in std::cell for single-threaded code.
     24 
     25 - Mutex<T> and RwLock<T> in std::sync for synchronized mutation across threads.
     26 
     27 - Atomic types like AtomicUsize for lock-free concurrent mutation.
     28 
     29 ## Example
     30 
     31 A simple example is a struct that keeps a usage counter even when you only pass
     32 around
     33 
     34 ```rust
     35 use std::cell::Cell;
     36 
     37 struct Counter {
     38     value: Cell<u32>,
     39 }
     40 
     41 impl Counter {
     42     fn inc(&self) {
     43         self.value.set(self.value.get() + 1);
     44     }
     45 }
     46 ```
     47 
     48 Here, inc takes &self but still mutates the internal value.
     49 
     50 [Reference](https://mara.nl/atomics/basics.html#interior-mutability)