Shortcut combining from_str and Display implementations?

kinda common use-case I would think... where an enum is serialized and deserialized from/to the same string characters.

Has the Rust community ever thought of adding a shortcut, to just be able to say in less code:
Fruit::Apple <--> "apple"

use std::fmt;
use std::str::FromStr;

pub enum Fruit {
    Apple,
    Carrot,
}

impl std::str::FromStr for Fruit {
    type Err = Error;
    fn from_str(input: &str) -> Result<Fruit, Self::Err> {
        match input {
            "apple => Ok(Fruit::Apple),
            "carrot" => Ok(Fruit::Carrot),
            other => Err(format!("Unknown fruit {other}").into()),
        }
    }
}

impl fmt::Display for Fruit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       match self {
           Fruit::Apple => write!(f, "apple"),
           Fruit::Carrot => write!(f, "carrot"),
       }
    }
}

Or could there be an implementation that covers both when it's the same characters from/to the enum to at least cut 50% of the amount of code?

I understand a cheap trick is just auto deriving Debug, but that doesn't let you customize the string representation at all. Sorry if this is a duplicate post, it seems like a common-place thing but no related posts matched I promise!

You can use strum to derive both Display (Display in strum - Rust) and FromStr (EnumString in strum - Rust)

5 Likes

that's brilliant and exactly what I was hoping for. Gosh stuff this good deserves its place in std :wink:

the only annoyance is I also am using serde so kinda redundant specifying:

#[strum(serialize = "apple")]
#[serde(rename = "apple")]

And it's not always just a lowercase translation. Ah looks like there's an open issue for this:

2 Likes

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.