|
| 1 | +// Say we're writing a game where you can buy items with tokens. All items cost |
| 2 | +// 5 tokens, and whenever you purchase items there is a processing fee of 1 |
| 3 | +// token. A player of the game will type in how many items they want to buy, |
| 4 | +// and the `total_cost` function will calculate the total number of tokens. |
| 5 | +// Since the player typed in the quantity, though, we get it as a string-- and |
| 6 | +// they might have typed anything, not just numbers! |
| 7 | + |
| 8 | +// Right now, this function isn't handling the error case at all (and isn't |
| 9 | +// handling the success case properly either). What we want to do is: |
| 10 | +// if we call the `parse` function on a string that is not a number, that |
| 11 | +// function will return a `ParseIntError`, and in that case, we want to |
| 12 | +// immediately return that error from our function and not try to multiply |
| 13 | +// and add. |
| 14 | + |
| 15 | +// There are at least two ways to implement this that are both correct-- but |
| 16 | +// one is a lot shorter! Scroll down for hints to both ways. |
| 17 | + |
| 18 | +use std::num::ParseIntError; |
| 19 | + |
| 20 | +pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { |
| 21 | + let processing_fee = 1; |
| 22 | + let cost_per_item = 5; |
| 23 | + let qty = item_quantity.parse::<i32>(); |
| 24 | + |
| 25 | + Ok(qty * cost_per_item + processing_fee) |
| 26 | +} |
| 27 | + |
| 28 | +#[cfg(test)] |
| 29 | +mod tests { |
| 30 | + use super::*; |
| 31 | + |
| 32 | + #[test] |
| 33 | + fn item_quantity_is_a_valid_number() { |
| 34 | + assert_eq!( |
| 35 | + total_cost("34"), |
| 36 | + Ok(171) |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + #[test] |
| 41 | + fn item_quantity_is_an_invalid_number() { |
| 42 | + assert_eq!( |
| 43 | + total_cost("beep boop").unwrap_err().to_string(), |
| 44 | + "invalid digit found in string" |
| 45 | + ); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +// One way to handle this is using a `match` statement on |
| 66 | +// `item_quantity.parse::<i32>()` where the cases are `Ok(something)` and |
| 67 | +// `Err(something)`. This pattern is very common in Rust, though, so there's |
| 68 | +// a `try!` macro that does pretty much what you would make that match statement |
| 69 | +// do for you! Take a look at this section of the Error Handling chapter: |
| 70 | +// https://doc.rust-lang.org/stable/book/error-handling.html#the-try-macro |
| 71 | +// and give it a `try!` |
0 commit comments