String to/from enum

What's an idiomatic way to convert strings to an enum and enum to a string?

Beginning with the string to enum I tried:

use std::convert::TryFrom;

#[derive(Debug,Clone)]
pub enum FSOType {
  Reg,
  Dir,
  Sym
}

impl TryFrom<&str> for FSOType {
  type Error = &'static str;

  fn try_from(s: &str) -> Result<Self, Self::Error> {
    match s {
      "reg" => Ok(FSOType::Reg),
      "dir" => Ok(FSOType::Dir),
      "sym" => Ok(FSOType::Sym),
      _ => Err("Unknown FSOType")
    }
  }
}

While this compiles I end up in the awkward situation of not actually being able to call it.

Did you try to call it like this? What was the problem?

fn main() {
    let reg = FSOType::try_from("reg").unwrap();
    println!("{:?}", reg);
}
1 Like

Argh! I was doing it right all along, but I didn't read the final lines of the error output.

help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
   |
5  | use std::convert::TryFrom;

(I have the enum and TryFrom in a separate module).

For this case, it's better to use FromStr:

use anyhow::{bail, Result};
use std::str::FromStr;

impl FromStr for FSOType {
    type Error = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "reg" => Ok(FSOType::Reg),
            "dir" => Ok(FSOType::Dir),
            "sym" => Ok(FSOType::Sym),
            _ => bail!("Unknown FSOType"),
        }
    }
}

It's recommended that error types implement Error. Here, I used anyhow::Error for simplicity.

Now, you can simply use parse to parse strings into FSOType.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.