Solution

  1. #![allow(dead_code)]
  2. pub struct User {
  3.     name: String,
  4.     age: u32,
  5.     height: f32,
  6.     visit_count: usize,
  7.     last_blood_pressure: Option<(u32, u32)>,
  8. }
  9. pub struct Measurements {
  10.     height: f32,
  11.     blood_pressure: (u32, u32),
  12. }
  13. pub struct HealthReport<'a> {
  14.     patient_name: &'a str,
  15.     visit_count: u32,
  16.     height_change: f32,
  17.     blood_pressure_change: Option<(i32, i32)>,
  18. }
  19. impl User {
  20.     pub fn new(name: String, age: u32, height: f32) -> Self {
  21.         Self { name, age, height, visit_count: 0, last_blood_pressure: None }
  22.     }
  23.     pub fn visit_doctor(&mut self, measurements: Measurements) -> HealthReport {
  24.         self.visit_count += 1;
  25.         let bp = measurements.blood_pressure;
  26.         let report = HealthReport {
  27.             patient_name: &self.name,
  28.             visit_count: self.visit_count as u32,
  29.             height_change: measurements.height - self.height,
  30.             blood_pressure_change: match self.last_blood_pressure {
  31.                 Some(lbp) => {
  32.                     Some((bp.0 as i32 - lbp.0 as i32, bp.1 as i32 - lbp.1 as i32))
  33.                 }
  34.                 None => None,
  35.             },
  36.         };
  37.         self.height = measurements.height;
  38.         self.last_blood_pressure = Some(bp);
  39.         report
  40.     }
  41. }
  42. fn main() {
  43.     let bob = User::new(String::from("Bob"), 32, 155.2);
  44.     println!("I'm {} and my age is {}", bob.name, bob.age);
  45. }
  46. #[test]
  47. fn test_visit() {
  48.     let mut bob = User::new(String::from("Bob"), 32, 155.2);
  49.     assert_eq!(bob.visit_count, 0);
  50.     let report =
  51.         bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (120, 80) });
  52.     assert_eq!(report.patient_name, "Bob");
  53.     assert_eq!(report.visit_count, 1);
  54.     assert_eq!(report.blood_pressure_change, None);
  55.     assert!((report.height_change - 0.9).abs() < 0.00001);
  56.     let report =
  57.         bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (115, 76) });
  58.     assert_eq!(report.visit_count, 2);
  59.     assert_eq!(report.blood_pressure_change, Some((-5, -4)));
  60.     assert_eq!(report.height_change, 0.0);
  61. }