January 2019
Intermediate to advanced
520 pages
14h 32m
English
Our Color type has to be convertible from a string. We can do this by implementing the FromStr trait, which makes it possible to call the parse method of str to parse the struct from a string:
impl FromStr for Color { type Err = ColorError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "white" => Ok(WHITE.to_owned()), "black" => Ok(BLACK.to_owned()), s if s.starts_with("#") && s.len() == 7 => { let red = u8::from_str_radix(&s[1..3], 16)?; let green = u8::from_str_radix(&s[3..5], 16)?; let blue = u8::from_str_radix(&s[5..7], 16)?; Ok(Color { red, green, blue }) }, other => { Err(ColorError::InvalidValue { value: other.to_owned() }) }, } }}
In this implementation, we use a match expression with four branches ...
Read now
Unlock full access