diff options
| author | Hunter Kvalevog <hunter@kvog.sh> | 2026-09-27 12:11:32 -0500 |
|---|---|---|
| committer | Hunter Kvalevog <hunter@kvog.sh> | 2026-09-27 12:11:32 -0500 |
| commit | b9b008c1d4a730335bdc9d465b0fdf7869fb09d4 (patch) | |
| tree | e9695905445b4bab89c07b8662fe40207b74c288 /rustlings/solutions/13_error_handling/errors2.rs | |
| parent | 1da0f56d76e5d5117eac05af092bf0ab58b14c8f (diff) | |
rustlings: complete 13
Diffstat (limited to 'rustlings/solutions/13_error_handling/errors2.rs')
| -rw-r--r-- | rustlings/solutions/13_error_handling/errors2.rs | 58 |
1 files changed, 56 insertions, 2 deletions
diff --git a/rustlings/solutions/13_error_handling/errors2.rs b/rustlings/solutions/13_error_handling/errors2.rs index dcf2377..f0e144e 100644 --- a/rustlings/solutions/13_error_handling/errors2.rs +++ b/rustlings/solutions/13_error_handling/errors2.rs @@ -1,4 +1,58 @@ +// Say we're writing a game where you can buy items with tokens. All items cost +// 5 tokens, and whenever you purchase items there is a processing fee of 1 +// token. A player of the game will type in how many items they want to buy, and +// the `total_cost` function will calculate the total cost of the items. Since +// the player typed in the quantity, we get it as a string. They might have +// typed anything, not just numbers! +// +// Right now, this function isn't handling the error case at all. What we want +// to do is: If we call the `total_cost` function on a string that is not a +// number, that function will return a `ParseIntError`. In that case, we want to +// immediately return that error from our function and not try to multiply and +// add. +// +// There are at least two ways to implement this that are both correct. But one +// is a lot shorter! + +use std::num::ParseIntError; + +#[allow(unused_variables, clippy::question_mark)] +fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { + let processing_fee = 1; + let cost_per_item = 5; + + // Added `?` to propagate the error. + let qty = item_quantity.parse::<i32>()?; + // ^ added + + // Equivalent to this verbose version: + let qty = match item_quantity.parse::<i32>() { + Ok(v) => v, + Err(e) => return Err(e), + }; + + Ok(qty * cost_per_item + processing_fee) +} + fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + use std::num::IntErrorKind; + + #[test] + fn item_quantity_is_a_valid_number() { + assert_eq!(total_cost("34"), Ok(171)); + } + + #[test] + fn item_quantity_is_an_invalid_number() { + assert_eq!( + total_cost("beep boop").unwrap_err().kind(), + &IntErrorKind::InvalidDigit, + ); + } } |