errors2.rs (1724B)
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, and 4 // the `total_cost` function will calculate the total cost of the items. Since 5 // the player typed in the quantity, we get it as a string. They might have 6 // typed anything, not just numbers! 7 // 8 // Right now, this function isn't handling the error case at all. What we want 9 // to do is: If we call the `total_cost` function on a string that is not a 10 // number, that function will return a `ParseIntError`. In that case, we want to 11 // immediately return that error from our function and not try to multiply and 12 // add. 13 // 14 // There are at least two ways to implement this that are both correct. But one 15 // is a lot shorter! 16 17 use std::num::ParseIntError; 18 19 fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { 20 let processing_fee = 1; 21 let cost_per_item = 5; 22 23 // TODO: Handle the error case as described above. 24 let qty = item_quantity.parse::<i32>()?; 25 26 // let qty = match item_quantity.parse::<i32>() { 27 // Ok(v) => v, 28 // Err(e) => return Err(e), 29 // }; 30 31 Ok(qty * cost_per_item + processing_fee) 32 } 33 34 fn main() { 35 // You can optionally experiment here. 36 } 37 38 #[cfg(test)] 39 mod tests { 40 use super::*; 41 use std::num::IntErrorKind; 42 43 #[test] 44 fn item_quantity_is_a_valid_number() { 45 assert_eq!(total_cost("34"), Ok(171)); 46 } 47 48 #[test] 49 fn item_quantity_is_an_invalid_number() { 50 assert_eq!( 51 total_cost("beep boop").unwrap_err().kind(), 52 &IntErrorKind::InvalidDigit, 53 ); 54 } 55 }