rust / intermediate
Snippet
Interior Mutability with RefCell<T>
RefCell<T> provides interior mutability by moving borrow checking from compile time to runtime. While Ref<T> and RefMut<T> enforce borrowing rules at runtime, RefCell<T> allows mutation of the inner value even through immutable references. This pattern is useful when you need to mutate data from multiple places but want to defer borrowing decisions. However, violating borrow rules will cause a panic at runtime rather than a compile error.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use std::cell::RefCell;struct Counter {value: RefCell<i32>,}impl Counter {fn new() -> Self {Counter { value: RefCell::new(0) }}fn increment(&self) {*self.value.borrow_mut() += 1;}fn get(&self) -> i32 {*self.value.borrow()}}fn main() {let counter = Counter::new();counter.increment();counter.increment();println!("Count: {}", counter.get());}
Breakdown
1
use std::cell::RefCell;
Import RefCell from the cell module for interior mutability patterns
2
value: RefCell<i32>
Wrap the i32 in RefCell to allow mutation through &self
3
*self.value.borrow_mut() += 1;
borrow_mut() returns a RefMut<i32> which dereferences to modify the inner value
4
*self.value.borrow()
borrow() returns an immutable Ref<i32> to read the value safely