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!