Skip to content

Instantly share code, notes, and snippets.

@fu5ha
Last active August 24, 2020 06:43
Show Gist options
  • Save fu5ha/198213201b9b815fb6743b4df70a505e to your computer and use it in GitHub Desktop.
Save fu5ha/198213201b9b815fb6743b4df70a505e to your computer and use it in GitHub Desktop.
#[derive(Debug)]
enum PersonParseError {
Malformed,
AgeParseError(std::string::ParseError),
}
impl fmt::Display for PersonParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
PersonParseError::Malformed => write!(f, "Malformed or empty input string"),
PersonParseError::AgeParseError(e) => write!(f, "Error parsing age: {}", e),
}
}
}
impl Error for PersonParseError {}
impl Person {
fn from_string(s: &str) -> Result<Person, PersonParseError> {
let parts = s.split(",");
let name = parts
.next()
.ok_or(Err(PersonParseError::Malformed))?;
let age = parts
.next()
.ok_or(Err(PersonParseError::Malformed))?
.parse::<usize>().map_err(|e| PersonParseError::AgeParseError(e))?;
Ok(Person{
name: name,
age: age
})
}
}
impl From<&str> for Person {
fn from(s: &str) -> Person {
Person::from_string(s).unwrap_or_else(Default::default)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment