alexxroche/rustlings-idiomatic-solutions

Alternative answer for from_str.rs

Closed this issue · 1 comments

Here is my solution for conversions/from_str.rs, may be you'd like to add it to the answers:

impl FromStr for Person {
    type Err = String;
    fn from_str(s: &str) -> Result<Person, Self::Err> {
        match s.split(',').collect::<Vec<&str>>()[..] {
            [name, age] if name.len() > 0 => age
                .parse()
                .map(|age| Self {
                    name: name.to_string(),
                    age,
                })
                .map_err(|x| "failed".to_string()),
            _ => Err("failed".to_string()),
        }
    }
}

Thank you. I've published it https://github.com/alexxroche/rustlings-idiomatic-solutions/blob/master/exercises/conversions/from_str.rs_/from_str_condensed.rs and called it "condensed" because it is 300 characters smaller than the average of the existing solutions.

I did hesitate for a moment, to add this because I wondered if it was too advanced for beginners to parse and understand the logic flow in such a tidy package. I concluded that it was a lovely example of method chaining that can only benefit those learning.