From 7ccd09ed3d991d1eca2680e0405e2369795d5831 Mon Sep 17 00:00:00 2001 From: Phan Huy Hoang Date: Sat, 7 Jan 2023 00:53:31 +0700 Subject: [PATCH] [Add] exercises/error_handling --- exercises/error_handling/errors1.rs | 9 +++------ exercises/error_handling/errors2.rs | 6 ++---- exercises/error_handling/errors3.rs | 6 +++--- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index bcee9723..1df898fa 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -5,14 +5,11 @@ // construct to `Option` that can be used to express error conditions. Let's use it! // Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -pub fn generate_nametag_text(name: String) -> Option { +pub fn generate_nametag_text(name: String) -> Result { if name.is_empty() { - // Empty names aren't allowed. - None + Err("`name` was empty; it must be nonempty.".into()) } else { - Some(format!("Hi! My name is {}", name)) + Ok(format!("Hi! My name is {}", name)) } } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index 1cd8fc66..f581de44 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -17,16 +17,14 @@ // one is a lot shorter! // Execute `rustlings hint errors2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::num::ParseIntError; pub fn total_cost(item_quantity: &str) -> Result { let processing_fee = 1; let cost_per_item = 5; - let qty = item_quantity.parse::(); + let qty = item_quantity.parse::()?; - Ok(qty * cost_per_item + processing_fee) + Ok(qty * cost_per_item + processing_fee.ok) } #[cfg(test)] diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index a2d2d190..b668f50e 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -4,11 +4,9 @@ // Why not? What should we do to fix it? // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::num::ParseIntError; -fn main() { +fn main() -> Result<(), ParseIntError> { let mut tokens = 100; let pretend_user_input = "8"; @@ -20,6 +18,8 @@ fn main() { tokens -= cost; println!("You now have {} tokens.", tokens); } + + Ok(()) } pub fn total_cost(item_quantity: &str) -> Result {