rust / intermediate
Snippet
Interior Mutability with Cell Types
Cell types enable mutable data sharing in single-threaded scenarios where borrowing rules would normally prevent it. Cell<T> works with Copy types only, providing set and get methods. RefCell<T> wraps any type and tracks borrow checks at runtime instead of compile time, panicking if you violate borrowing rules. Use these when you need interior mutability but can guarantee single-thread access.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::cell::Cell;use std::cell::RefCell;fn main() {let data = Cell::new(5);data.set(10);println!("Cell value: {}", data.get());let ref_data = RefCell::new(vec![1, 2, 3]);ref_data.borrow_mut().push(4);println!("RefCell: {:?}", ref_data.borrow());let mut count = 5;let counter = Cell::new(count);count = 10;println!("Counter unchanged: {}", counter.get());}
Breakdown
1
let data = Cell::new(5)
Creates a Cell containing i32. Cell<T> only works for Copy types like i32, bool, char
2
data.set(10)
Cell allows mutation even through shared reference because it manages access internally
3
ref_data.borrow_mut().push(4)
borrow_mut returns mutable reference enabling mutation. Borrow tracker ensures only one mutable borrow at a time
4
count = 10; println!("{}", counter.get())
Changing count doesn't affect Cell since Cell stores its own copy for Copy types