rust / intermediate
Snippet
Interior Mutability with RefCell
RefCell<T> provides 'interior mutability', a pattern allowing you to mutate data even when you have an immutable reference to that data. Borrowing rules are enforced at runtime rather than compile time.
snippet.rs
1
2
3
4
5
6
7
8
use std::cell::RefCell;let value = RefCell::new(5);{let mut borrowed_value = value.borrow_mut();*borrowed_value += 10;}println!("Value: {:?}", value.borrow());
Breakdown
1
RefCell::new(5)
Wraps a value in a RefCell to enable interior mutability.
2
value.borrow_mut()
Dynamically checks for existing borrows and returns a mutable reference.