From a15ebedd0622f79dd8245ea98f64619a7ad8efc0 Mon Sep 17 00:00:00 2001 From: Denis Nutiu Date: Tue, 12 Nov 2024 21:38:37 +0200 Subject: [PATCH] record progress: from str --- exercises/23_conversions/from_str.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/exercises/23_conversions/from_str.rs b/exercises/23_conversions/from_str.rs index 4b1aaa2..09b20c2 100644 --- a/exercises/23_conversions/from_str.rs +++ b/exercises/23_conversions/from_str.rs @@ -7,6 +7,7 @@ use std::num::ParseIntError; use std::str::FromStr; +use crate::ParsePersonError::{BadLen, ParseInt}; #[derive(Debug, PartialEq)] struct Person { @@ -25,7 +26,7 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// TODO: Complete this `From` implementation to be able to parse a `Person` +// Complete this `From` implementation to be able to parse a `Person` // out of a string in the form of "Mark,20". // Note that you'll need to parse the age component into a `u8` with something // like `"4".parse::()`. @@ -41,7 +42,23 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; - fn from_str(s: &str) -> Result {} + fn from_str(s: &str) -> Result { + let components: Vec<&str> = s.split(",").collect(); + if components.len() != 2 { + return Err(BadLen); + } + let name = components.get(0).unwrap(); + let age_result = components.get(1).unwrap().parse::().map_err(|e| ParseInt(e))?; + + if name == &"" { + return Err(ParsePersonError::NoName) + } + + Ok(Person { + name: name.to_string(), + age: age_result, + }) + } } fn main() {