Blood Alcohol Calculator
Calculate the blood alcohol content (BAC) based on 5 inputs:
- body weight,
- gender,
- number of drinks,
- amount of alcohol by volume of the drink consumed, and
- amount of time since the last drink.
Finally, decide if it's legal to drive by compare the BAC with a fixed threshold (0.08).
The first step in solving this exercise is to read the input. We already have code to read
numbers, so the only new thing is to read the gender. We can read and store the gender as a string,
but it's better to have a dedicated data type and early validation.
Here we use an enum for gender and implement FromStr trait to parse it:
enum Gender {
Male,
Female,
}
struct ParseGenderError {}
impl FromStr for Gender {
type Err = ParseGenderError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_uppercase().as_str() {
"M" | "MALE" => Ok(Gender::Male),
"F" | "FEMALE" => Ok(Gender::Female),
_ => Err(ParseGenderError {}),
}
}
}
The code above features the FromStr trait and matching on multiple alternatives using a vertical bar |.
After reading the input, it is straightforward to calculate the BAC.
let alcohol_distribution_ratio = match gender {
Gender::Male => 0.73,
Gender::Female => 0.66,
};
let bac = alcohol_amount * 5.14 / (body_weight * alcohol_distribution_ratio) - 0.015 * hours;