Last active
September 30, 2022 23:17
-
-
Save mwrites/9b979b1d493c07b07a3b5369b93bdcd6 to your computer and use it in GitHub Desktop.
rust split option to result to value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::num::ParseIntError; | |
use std::str::FromStr; | |
#[derive(Debug, PartialEq)] | |
enum ParsePersonError { | |
// Empty input string | |
Empty, | |
// Incorrect number of fields | |
BadLen, | |
// Empty name field | |
NoName, | |
// Wrapped error from parse::<usize>() | |
ParseInt(ParseIntError), | |
} | |
#[derive(Debug, PartialEq, Default)] | |
struct Person { | |
name: String, | |
age: usize, | |
} | |
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 mut split = s.split(",").collect::<Vec<_>>(); | |
let mut person = Person::default(); | |
if split.len() != 2 { | |
return Err(ParsePersonError::BadLen); | |
} | |
let mut split_iter = split.into_iter(); | |
person.name = split_iter | |
.next() | |
.filter(|s| s.len() > 0) | |
.map(|s| s.to_string()) | |
.ok_or(ParsePersonError::NoName)?; | |
person.age = split_iter | |
.next() | |
.ok_or(ParsePersonError::BadLen)? | |
.parse::<usize>() | |
.map_err(|e| { | |
ParsePersonError::ParseInt(e) | |
})?; | |
Ok(person) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment