-
In the bin folder, create a file called interior_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 fn publish_news(msg: &str, sender: &EmailSender, customers: &
[Customer]) -> Option<i32> {
20 let mut count = 0;
21 let mut mail = Email {
22 from: "Rust Newsletter".to_string(),
23 to: "".to_string(),
24 msg: msg.to_string(),
25 };
26 for customer in customers {
27 if !customer.wants_news {
28 continue;
29 }
30 mail.to = customer.address.to_string();
31 if...