2016-06-21 17:07:21 +03:00
|
|
|
// 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
|
2023-05-29 20:39:08 +03:00
|
|
|
// token. A player of the game will type in how many items they want to buy, and
|
2023-10-13 22:47:38 +03:00
|
|
|
// the `total_cost` function will calculate the total cost of the items. Since
|
2024-06-26 16:36:14 +03:00
|
|
|
// the player typed in the quantity, we get it as a string. They might have
|
|
|
|
// typed anything, not just numbers!
|
2023-05-29 20:39:08 +03:00
|
|
|
//
|
2016-06-21 17:07:21 +03:00
|
|
|
// Right now, this function isn't handling the error case at all (and isn't
|
2024-06-26 16:36:14 +03:00
|
|
|
// handling the success case properly either). What we want to do is: If we call
|
2023-08-14 22:49:28 +03:00
|
|
|
// the `total_cost` function on a string that is not a number, that function
|
2024-06-26 16:36:14 +03:00
|
|
|
// will return a `ParseIntError`. In that case, we want to immediately return
|
|
|
|
// that error from our function and not try to multiply and add.
|
2023-05-29 20:39:08 +03:00
|
|
|
//
|
2024-06-26 16:36:14 +03:00
|
|
|
// There are at least two ways to implement this that are both correct. But one
|
2023-05-29 20:39:08 +03:00
|
|
|
// is a lot shorter!
|
2016-06-21 17:07:21 +03:00
|
|
|
|
|
|
|
use std::num::ParseIntError;
|
|
|
|
|
2024-05-22 16:04:12 +03:00
|
|
|
fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
|
2016-06-21 17:07:21 +03:00
|
|
|
let processing_fee = 1;
|
|
|
|
let cost_per_item = 5;
|
2024-06-26 16:36:14 +03:00
|
|
|
|
|
|
|
// TODO: Handle the error case as described above.
|
2016-06-21 17:07:21 +03:00
|
|
|
let qty = item_quantity.parse::<i32>();
|
|
|
|
|
|
|
|
Ok(qty * cost_per_item + processing_fee)
|
|
|
|
}
|
|
|
|
|
2024-04-17 23:46:21 +03:00
|
|
|
fn main() {
|
|
|
|
// You can optionally experiment here.
|
|
|
|
}
|
|
|
|
|
2016-06-21 17:07:21 +03:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2024-06-26 16:36:14 +03:00
|
|
|
use std::num::IntErrorKind;
|
2016-06-21 17:07:21 +03:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn item_quantity_is_a_valid_number() {
|
2019-05-22 14:48:32 +03:00
|
|
|
assert_eq!(total_cost("34"), Ok(171));
|
2016-06-21 17:07:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn item_quantity_is_an_invalid_number() {
|
|
|
|
assert_eq!(
|
2024-06-26 16:36:14 +03:00
|
|
|
total_cost("beep boop").unwrap_err().kind(),
|
|
|
|
&IntErrorKind::InvalidDigit,
|
2016-06-21 17:07:21 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|