trait
FromStr — define parsing for a type
Implement this trait to support parse for your own type. Choose an error type and define exactly which strings are accepted; it does not promise round-trip compatibility with Display. Expected stdout (not executed): 2 Err("unknown level") Common mistake: Returning references to arbitrary input data through a FromStr implementation without a suitable lifetime contract.
Formal Syntax & Structure
rust syntaxrust
fn from_str(s: &str) -> Result<Self, Self::Err>Working Example
Example Snippetrust
fn main() { use std::str::FromStr; #[derive(Debug)] struct Level(u8); impl FromStr for Level { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "low" => Ok(Level(1)), "high" => Ok(Level(2)), _ => Err("unknown level") } } } let level: Level = "high".parse().unwrap(); println!("{}", level.0); println!("{:?}", "other".parse::<Level>());}