From ae1c7a907ccc2e08a84a480777dbe45580003f61 Mon Sep 17 00:00:00 2001 From: horaoen Date: Thu, 1 Feb 2024 18:13:03 +0800 Subject: [PATCH] update --- exercises/23_conversions/from_into.rs | 12 ++++++++++-- exercises/23_conversions/from_str.rs | 20 ++++++++++++++++++-- exercises/23_conversions/using_as.rs | 4 +--- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/exercises/23_conversions/from_into.rs b/exercises/23_conversions/from_into.rs index 60911f3e..b6f7e0c5 100644 --- a/exercises/23_conversions/from_into.rs +++ b/exercises/23_conversions/from_into.rs @@ -40,10 +40,18 @@ impl Default for Person { // If while parsing the age, something goes wrong, then return the default of // Person Otherwise, then return an instantiated Person object with the results -// I AM NOT DONE - impl From<&str> for Person { fn from(s: &str) -> Person { + let v: Vec<&str> = s.split(',').collect(); + if v.len() >= 2 && v[0].len() > 0 { + if let Ok(age) = v[1].parse::() { + return Person { + name: v[0].to_string(), + age, + }; + } + } + Person::default() } } diff --git a/exercises/23_conversions/from_str.rs b/exercises/23_conversions/from_str.rs index 34472c32..ffbf4e0a 100644 --- a/exercises/23_conversions/from_str.rs +++ b/exercises/23_conversions/from_str.rs @@ -31,8 +31,6 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// I AM NOT DONE - // Steps: // 1. If the length of the provided string is 0, an error should be returned // 2. Split the given string on the commas present in it @@ -52,6 +50,24 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s.is_empty() { + return Err(ParsePersonError::Empty); + } + let v: Vec<&str> = s.split(',').collect(); + if v.len() == 2 { + if v[0].is_empty() { + return Err(ParsePersonError::NoName); + } + match v[1].parse::() { + Ok(age) => Ok(Person { + name: v[0].to_string(), + age, + }), + Err(err) => Err(ParsePersonError::ParseInt(err)), + } + } else { + Err(ParsePersonError::BadLen) + } } } diff --git a/exercises/23_conversions/using_as.rs b/exercises/23_conversions/using_as.rs index 414cef3a..a9f1e449 100644 --- a/exercises/23_conversions/using_as.rs +++ b/exercises/23_conversions/using_as.rs @@ -10,11 +10,9 @@ // Execute `rustlings hint using_as` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - fn average(values: &[f64]) -> f64 { let total = values.iter().sum::(); - total / values.len() + total / values.len() as f64 } fn main() {