-1

I know how to do it in Java.

It seems I need to implement TryFrom or something like that.

enum ROMAN {
    I = 1,
    V = 5,
    X = 10,
    L = 50,
    C = 100,
    D = 500,
    M = 1000
}

I want to get value using by enums name.

println!("{:?}", ROMAN::valueOf("M")); // It should be `1000`
Herohtar
  • 5,347
  • 4
  • 31
  • 41

1 Answers1

0

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.

Masklinn
  • 34,759
  • 3
  • 38
  • 57