Either implement FromStr
or TryFrom
manually, or use something like enum_derive
which provides these features.
Or just add a bespoke value_of
method on your enum without bothering with traits.
Or do all of it, though that seems a bit much
impl Roman {
pub fn value_of(s: &str) -> Option<Self> {
Some(match s {
"I" => Self::I,
"V" => Self::V,
"X" => Self::X,
"L" => Self::L,
"C" => Self::C,
"D" => Self::D,
"M" => Self::M,
_ => return None,
})
}
}
impl FromStr for Roman {
type Err = (); // should probably provide something more useful
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::value_of(s).ok_or(())
}
}
impl TryFrom<&str> for Roman {
type Error = ();
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::value_of(s).ok_or(())
}
}
println!("{:?}", ROMAN::valueOf("M")); // It should be `1000`
It's never going to be 1000
because that's not how Rust works. You'd need to handle the error then convert the success value to its discriminant.