Exercise: Health Statistics

You’re working on implementing a health-monitoring system. As part of that, you need to keep track of users’ health statistics.

You’ll start with a stubbed function in an impl block as well as a User struct definition. Your goal is to implement the stubbed out method on the User struct defined in the impl block.

Copy the code below to https://play.rust-lang.org/ and fill in the missing method:

  1. // TODO: remove this when you're done with your implementation.
  2. #![allow(unused_variables, dead_code)]
  3. #![allow(dead_code)]
  4. pub struct User {
  5.     name: String,
  6.     age: u32,
  7.     height: f32,
  8.     visit_count: usize,
  9.     last_blood_pressure: Option<(u32, u32)>,
  10. }
  11. pub struct Measurements {
  12.     height: f32,
  13.     blood_pressure: (u32, u32),
  14. }
  15. pub struct HealthReport<'a> {
  16.     patient_name: &'a str,
  17.     visit_count: u32,
  18.     height_change: f32,
  19.     blood_pressure_change: Option<(i32, i32)>,
  20. }
  21. impl User {
  22.     pub fn new(name: String, age: u32, height: f32) -> Self {
  23.         Self { name, age, height, visit_count: 0, last_blood_pressure: None }
  24.     }
  25.     pub fn visit_doctor(&mut self, measurements: Measurements) -> HealthReport {
  26.         todo!("Update a user's statistics based on measurements from a visit to the doctor")
  27.     }
  28. }
  29. fn main() {
  30.     let bob = User::new(String::from("Bob"), 32, 155.2);
  31.     println!("I'm {} and my age is {}", bob.name, bob.age);
  32. }
  33. #[test]
  34. fn test_visit() {
  35.     let mut bob = User::new(String::from("Bob"), 32, 155.2);
  36.     assert_eq!(bob.visit_count, 0);
  37.     let report =
  38.         bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (120, 80) });
  39.     assert_eq!(report.patient_name, "Bob");
  40.     assert_eq!(report.visit_count, 1);
  41.     assert_eq!(report.blood_pressure_change, None);
  42.     assert!((report.height_change - 0.9).abs() < 0.00001);
  43.     let report =
  44.         bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (115, 76) });
  45.     assert_eq!(report.visit_count, 2);
  46.     assert_eq!(report.blood_pressure_change, Some((-5, -4)));
  47.     assert_eq!(report.height_change, 0.0);
  48. }