Update Ch15

This commit is contained in:
Unisko PENG 2023-05-11 14:30:55 +08:00
parent 5d41b08015
commit 5b4c6d8b1a
3 changed files with 47 additions and 10 deletions

View File

@ -25,14 +25,11 @@ where
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max >= 1.0 {
self.messenger.send("出错:你已超出你的配额!");
} else if percentage_of_max >= 0.9 {
self.messenger
.send("紧急警告:你已用掉你配额的 90% ");
} else if percentage_of_max >= 0.75 {
self.messenger
.send("警告:你已用掉你配额的 75% ");
match percentage_of_max {
max if max >= 1.0 => self.messenger.send("出错:你已超出你的配额!"),
max if max >= 0.9 => self.messenger.send("紧急警告:你已用掉你配额的 90% "),
max if max >= 0.75 => self.messenger.send("警告:你已用掉你配额的 75% "),
_ => {},
}
}
}

View File

@ -10,8 +10,17 @@ fn main() {
id: id_variable @ 3..=7,
} => println! ("找到位于范围内的一个 id: {}", id_variable),
Message::Hello { id: 10..=12 } => {
println! ("找到位于另一范围的一个 {}", id);
println! ("找到位于另一范围的一个 id");
},
Message::Hello { id } => println! ("找到别的一个 id: {}", id),
}
let level = 0.8;
match level {
l if l >= 1.0 => println! ("超出额度"),
l if l >= 0.9 => println! ("超出 90% 额度"),
l if l >= 0.75 => println! ("超出 75% 额度"),
_ => (),
}
}

View File

@ -857,7 +857,38 @@ Rust 没有像其他语言那样拥有对象Rust 也没有像其他一些语
文件名:`src/lib.rs`
```rust
{{#include ../projects/limit_tracker/src/lib.rs:40:}}
#[cfg(test)]
mod tests {
use super::*;
struct MockMessenger {
sent_messages: Vec<String>,
}
impl MockMessenger {
fn new() -> MockMessenger {
MockMessenger {
sent_messages: vec![],
}
}
}
impl Messenger for MockMessenger {
fn send(&self, message: &str) {
self.sent_messages.push(String::from(message));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
let mock_messenger = MockMessenger::new();
let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);
limit_tracker.set_value(80);
assert_eq!(mock_messenger.sent_messages.len(), 1);
}
}
```
*清单 15-21试图实现一个借用检查器不允许的 `MockMessenger`*