RefCell is a Rust standard-library container for interior mutability: it lets code change a value through an otherwise immutable access path. It resembles regular references, but checks borrowing rules at run time instead of compilation time. section 10.3.2 section 10.3
Use the borrowing methods as follows:
- Call borrow() for immutable access; multiple immutable borrows are allowed. section 10.3.2
- Call borrow_mut() for mutable access; one mutable borrow is allowed, but it cannot coexist with immutable borrows. section 10.3.2
- Use try_borrow_mut() when a second mutable borrow might occur; it returns an error instead of panicking. section 10.3.2 section 10.4
- Keep RefCell out of multithreaded code; unlike Mutex and RwLock, it does not provide the guards needed for shared-thread mutation. section 10.3.2 section 10.4
Mutating a field through an immutable user
A User can store active: RefCell<bool> and initialize it with RefCell::new(true). Mutation can then happen with *user_1.active.borrow_mut() = false, even when user_1 itself was not declared mutable. Holding one mutable borrow and requesting another compiles, but running the program immediately panics with BorrowMutError. section 10.3.2
use std::cell::RefCell;
#[derive(Debug)]
struct User {
id: u32,
year_registered: u32,
username: String,
active: RefCell<bool>, #1
}
fn main() {
let user_1 = User {
id: 1,
year_registered: 2020,
username: "User 1".to_string(),
active: RefCell::new(true),
};
println!("{:?}", user_1.active);
}
Inspect the minimal User definition and RefCell::new initialization before adding mutable borrows. section 10.3.2


