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>, } 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); }