解答

2. #![allow(dead_code)]
3. pub struct User {
4. name: String,
5. age: u32,
6. height: f32,
7. visit_count: usize,
8. last_blood_pressure: Option<(u32, u32)>,
9. }

11. pub struct Measurements {
12. height: f32,
13. blood_pressure: (u32, u32),
14. }

16. pub struct HealthReport<'a> {
17. patient_name: &'a str,
18. visit_count: u32,
19. height_change: f32,
20. blood_pressure_change: Option<(i32, i32)>,
21. }

23. impl User {
24. pub fn new(name: String, age: u32, height: f32) -> Self {
25. Self { name, age, height, visit_count: 0, last_blood_pressure: None }
26. }

28. pub fn visit_doctor(&mut self, measurements: Measurements) -> HealthReport {
29. self.visit_count += 1;
30. let bp = measurements.blood_pressure;
31. let report = HealthReport {
32. patient_name: &self.name,
33. visit_count: self.visit_count as u32,
34. height_change: measurements.height - self.height,
35. blood_pressure_change: match self.last_blood_pressure {
36. Some(lbp) => {
37. Some((bp.0 as i32 - lbp.0 as i32, bp.1 as i32 - lbp.1 as i32))
38. }
39. None => None,
40. },
41. };
42. self.height = measurements.height;
43. self.last_blood_pressure = Some(bp);
44. report
45. }
46. }

48. fn main() {
49. let bob = User::new(String::from("Bob"), 32, 155.2);
50. println!("I'm {} and my age is {}", bob.name, bob.age);
51. }

53. #[test]
54. fn test_visit() {
55. let mut bob = User::new(String::from("Bob"), 32, 155.2);
56. assert_eq!(bob.visit_count, 0);
57. let report =
58. bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (120, 80) });
59. assert_eq!(report.patient_name, "Bob");
60. assert_eq!(report.visit_count, 1);
61. assert_eq!(report.blood_pressure_change, None);

63. let report =
64. bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (115, 76) });

66. assert_eq!(report.visit_count, 2);
67. assert_eq!(report.blood_pressure_change, Some((-5, -4)));
68. }