Skip to content

Commit 686782f

Browse files
committed
finish from_str
1 parent c1470b9 commit 686782f

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

exercises/conversions/from_str.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,6 @@ enum ParsePersonError {
3131
ParseInt(ParseIntError),
3232
}
3333

34-
// I AM NOT DONE
35-
3634
// Steps:
3735
// 1. If the length of the provided string is 0, an error should be returned
3836
// 2. Split the given string on the commas present in it
@@ -52,6 +50,17 @@ enum ParsePersonError {
5250
impl FromStr for Person {
5351
type Err = ParsePersonError;
5452
fn from_str(s: &str) -> Result<Person, Self::Err> {
53+
if s.is_empty() { return Err(ParsePersonError::Empty); }
54+
let parts: Vec<_> = s.split(',').collect();
55+
if parts.len() != 2 {
56+
return Err(ParsePersonError::BadLen);
57+
}
58+
let (name, age_str) = (parts[0], parts[1]);
59+
if name.is_empty() { return Err(ParsePersonError::NoName); }
60+
match age_str.parse::<usize>() {
61+
Err(e) => Err(ParsePersonError::ParseInt(e)),
62+
Ok(age) => Ok(Person{name: name.to_string(), age: age}),
63+
}
5564
}
5665
}
5766

0 commit comments

Comments
 (0)