This commit is contained in:
horaoen 2024-02-01 18:13:03 +08:00
parent f3c8716ada
commit ae1c7a907c
3 changed files with 29 additions and 7 deletions

View File

@ -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::<usize>() {
return Person {
name: v[0].to_string(),
age,
};
}
}
Person::default()
}
}

View File

@ -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<Person, Self::Err> {
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::<usize>() {
Ok(age) => Ok(Person {
name: v[0].to_string(),
age,
}),
Err(err) => Err(ParsePersonError::ParseInt(err)),
}
} else {
Err(ParsePersonError::BadLen)
}
}
}

View File

@ -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::<f64>();
total / values.len()
total / values.len() as f64
}
fn main() {