Working with interior mutability
Although Rust's borrow checker is one of its biggest selling points, alongside its clever error-handling concept and impressive tooling, it cannot read minds yet. Sometimes you might have to take things into your own hands and borrow objects manually. This is done with the concept of interior mutability, which states that certain types can wrap objects while being non-mutable and still operate on them mutably.
How to do it...
In the
bin
folder, create a file calledinterior_mutability.rs
.Add the following code and run it with
cargo test --bin interior_mutability
:
1 trait EmailSender { 2 fn send_mail(&self, msg: &Email) -> Option<String>; 3 } 4 5 #[derive(Debug, Clone)] 6 struct Email { 7 from: String, 8 to: String, 9 msg: String, 10 } 11 12 #[derive(Debug)] 13 struct Customer { 14 address: String, 15 wants_news: bool, 16 } 17 18 // Send news to every customer that wants to receive them 19...