RefCell<T> provides interior mutability by moving borrow checking from compile time to runtime. While a &self reference normally prevents mutation, RefCell allows you to mutate the data it contains. The borrow_mut() method returns a mutable reference, and the RefCell tracks how many borrows are active. If you try to violate borrow rules at runtime (e.g., having two mutable borrows), the program will panic. This pattern is useful when you need to mutate data in scenarios where immutability is expected, such as in cached computations or when implementing data structures that require mutable access to their own data.
use std::cell::RefCell;struct Logger {messages: RefCell<Vec<String>>,max_size: usize,}impl Logger {fn new(max_size: usize) -> Self {Self {messages: RefCell::new(Vec::new()),max_size,}}fn log(&self, msg: &str) {let mut messages = self.messages.borrow_mut();if messages.len() >= self.max_size {messages.remove(0);}messages.push(msg.to_string());}fn get_messages(&self) -> Vec<String> {self.messages.borrow().clone()}}fn main() {let logger = Logger::new(3);logger.log("Application started");logger.log("User logged in");logger.log("Data loaded");logger.log("Request processed");println!("Logged messages: {:?}", logger.get_messages());}