In this lesson, you will learn how RefCell<T> allows you to bypass the compiler’s rigid borrow rules by moving the verification process from compile-time to runtime.
The Problem: Compile-Time Rigidity
Up until now, you have relied on the Rust compiler to enforce the borrowing rules: you can have either many immutable references or one mutable reference, but never both at the same time. This is enforced at compile-time.
Sometimes, however, you need to mutate a value even when you only have an immutable reference to it (this is known as Interior Mutability). If you try to do this with standard references, the borrow checker will stop your code from compiling.
The Solution: Runtime Checks
RefCell<T> provides a way to circumvent these rules by using "runtime borrow checking." Instead of checking your references when you build your program, RefCell keeps track of the active borrows while your program is actually running.
When you use RefCell, you use the .borrow() and .borrow_mut() methods to access the data.
use std::cell::RefCell;
let data = RefCell::new(10);
// We can create an immutable borrow
let first_ref = data.borrow();
// We can create another immutable borrow at the same time
let second_ref = data.borrow();
// This works! But if we tried to call .borrow_mut() while
// first_ref or second_ref were still in scope, the program
// would panic immediately at runtime.
Why use this?
If you violate the borrowing rules (e.g., trying to have a mutable and immutable borrow at the same time), the compiler will not stop you. Instead, your program will panic and crash when the code executes.
This is incredibly useful for complex state management, such as when you have a data structure that needs to modify its internal state while other parts of your program hold a reference to it. It trades the safety of compile-time errors for the flexibility required by certain complex design patterns.
Key Takeaway: RefCell<T> enforces borrowing rules at runtime, allowing you to mutate data even when it is technically shared, provided you do not violate the exclusive-access rules during program execution.