rust / intermediate
Snippet
Interior Mutability with Rc<RefCell<T>>
Rc<RefCell<T>> enables interior mutability in Rust, allowing mutation of data even when there are multiple immutable references. Rc provides reference counting for shared ownership, while RefCell defers borrow-checking to runtime. This pattern is useful when you need mutability behind an immutable interface.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::cell::RefCell;use std::rc::Rc;fn main() {let shared: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(vec![1, 2, 3]));let ref1 = Rc::clone(&shared);let ref2 = Rc::clone(&shared);ref1.borrow_mut().push(4);println!("Shared contents: {:?}", ref2.borrow());shared.borrow_mut().push(5);println!("Final contents: {:?}", shared.borrow());}
Breakdown
1
use std::cell::RefCell
Import RefCell which provides interior mutability with runtime borrow checking
2
use std::rc::Rc
Import Rc for reference-counted shared ownership
3
let shared = Rc::new(RefCell::new(vec![1, 2, 3]))
Create a RefCell-wrapped vector wrapped in Rc for shared ownership
4
let ref1 = Rc::clone(&shared)
Clone the Rc incrementing reference count, creating another reference to same data
5
ref1.borrow_mut().push(4)
Acquire mutable borrow and push 4 to the vector through ref1
6
println!("{:?}", ref2.borrow())
Access contents through ref2 showing the mutation is visible to all references