Rust normally makes data inside an immutable binding immutable too. RefCell is an interior-mutability container: it lets you mutate an owned value without making the container binding mutable. Unlike ordinary inherited mutability, this access is checked at runtime. section 9.4 section 9.5
Mutate an owned String
An immutable String cannot call push_str directly. Move it into a RefCell with `let value = RefCell::from(immutable_string);`, then call `value.borrow_mut().push_str("... or can it?");`. The binding `value` remains immutable, but the contained string changes. section 9.5
Listing 9.3 Using RefCell for interior mutability
let immutable_string = #1
String::from("This string cannot be changed");
// immutable_string.push_str("... or can it?"); // error: cannot borrow
`immutable_string` as mutable, as it is not declared as mutable #2
dbg!(&immutable_string);
let not_so_immutable_string = RefCell::from(immutable_string); #3
not_so_immutable_string
.borrow_mut()
.push_str("... or can it?"); #4
dbg!(¬_so_immutable_string);
The listing shows the failed direct mutation beside the RefCell::from and borrow_mut() alternative. section 9.5
Use RefCell when interior mutability serves a real ownership need, not simply to avoid thinking through borrowing. It does not provide shared ownership: Rc and Arc serve that separate purpose. Cell is another interior-mutability option, but changes its value by replacement rather than direct mutable access. section 9.4 section 10.8


