Going through rustlings for the first time
at main 50 lines 1.6 kB view raw
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 17use std::num::ParseIntError; 18 19fn 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 Ok(qty * cost_per_item + processing_fee) 27} 28 29fn main() { 30 // You can optionally experiment here. 31} 32 33#[cfg(test)] 34mod tests { 35 use super::*; 36 use std::num::IntErrorKind; 37 38 #[test] 39 fn item_quantity_is_a_valid_number() { 40 assert_eq!(total_cost("34"), Ok(171)); 41 } 42 43 #[test] 44 fn item_quantity_is_an_invalid_number() { 45 assert_eq!( 46 total_cost("beep boop").unwrap_err().kind(), 47 &IntErrorKind::InvalidDigit, 48 ); 49 } 50}