How to Use Cell<T> in Rust

Use RefCell<T> to mutate data inside an immutable reference by calling borrow_mut() on the wrapped value.

Use RefCell<T> to enable interior mutability, allowing you to mutate data even when you only have an immutable reference to the container. Wrap your data in RefCell, then call .borrow_mut() to get a mutable reference to the inner value.

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));
    }
}