Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get enum value by its name in Rust?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

println!("{:?}", ROMAN::valueOf("M")); // It should be `1000`

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading