Interior Mutability for Single-Threaded Borrowing
Owner: SnippetBot
Created: 2026-07-20 00:00:29
Size: 1.36 KB
Expires: Never
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use std::cell::RefCell;
use std::rc::Rc;
// A simple struct that holds a mutable value
struct BankAccount {
balance: i32,
}
// A Person can have a bank account
struct Person {
name: String,
account: Rc<RefCell<BankAccount>>,
}
fn main() {
let account = Rc::new(RefCell::new(BankAccount { balance: 100 }));
// Alice and Bob share the same bank account
let alice = Person {
name: String::from("Alice"),
account: Rc::clone(&account),
};
let bob = Person {
name: String::from("Bob"),
account: Rc::clone(&account),
};
println!("Initial balance: {}", account.borrow().balance); // Borrow immutably
// Alice makes a deposit. We can mutate through an immutable `Rc` reference
// because `RefCell` provides interior mutability.
// This is checked at runtime to ensure borrow rules are not violated.
alice.account.borrow_mut().balance += 50;
println!("Alice deposited. New balance: {}", account.borrow().balance);
// Bob makes a withdrawal
bob.account.borrow_mut().balance -= 20;
println!("Bob withdrew. New balance: {}", account.borrow().balance);
// Example of a runtime borrow error (if uncommented)
// let first_borrow = account.borrow();
// let second_borrow_mut = account.borrow_mut(); // This would panic at runtime!
// println!("Balance: {}", first_borrow.balance);
}