From 0e2dc5d96a32fd3ea4567abb3f59447222bbacbf Mon Sep 17 00:00:00 2001 From: Esteban Escobar Date: Sun, 22 Jan 2023 10:43:15 -0500 Subject: [PATCH] more progress --- REVISITS.md | 1 + exercises/error_handling/errors1.rs | 8 +++----- exercises/error_handling/errors2.rs | 12 +++++++++--- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/REVISITS.md b/REVISITS.md index 3982c070..a50ce4af 100644 --- a/REVISITS.md +++ b/REVISITS.md @@ -15,4 +15,5 @@ return results to new Vec vector 14) revisit all traits exercises 15) options1 (understand Some and None) 16) option2 (important to understand if let, while let statements alternative to match ). ChatGPT explanation was great. +17) errors2 make sure you understand error propagation but also the long-form solution (just for understanding). "The ? placed after a Result value is defined to work in almost the same way as the match expressions we defined to handle the Result values in Listing 9-6. If the value of the Result is an Ok, the value inside the Ok will get returned from this expression, and the program will continue. If the value is an Err, the Err will be returned from the whole function as if we had used the return keyword so the error value gets propagated to the calling code." diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index bcee9723..a4d16fef 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -5,14 +5,12 @@ // 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.".to_string()) } 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..97329174 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -17,16 +17,22 @@ // 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::()?; + //Long form solution + // match qty { + // Ok(q) => Ok(q * cost_per_item + processing_fee), + // Err(e) => Err(e) + // } + + //For short form we can use error propagation `?` shortcut Ok(qty * cost_per_item + processing_fee) + } #[cfg(test)]