Use RefCell<T> to wrap a value when you need to mutate it through an immutable reference, deferring borrow checking to runtime.
use std::cell::RefCell;
struct MockMessenger {
sent_messages: RefCell<Vec<String>>,
}
impl MockMessenger {
fn new() -> MockMessenger {
MockMessenger {
sent_messages: RefCell::new(vec![]),
}
}
fn send(&self, message: &str) {
self.sent_messages.borrow_mut().push(String::from(message));
}
}
The borrow_mut() method returns a mutable reference to the inner data, while borrow() returns an immutable one. This allows mutation inside methods that only take &self.