Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
macro_rules! enum_with_str_repr {
($enum_name:ident { $($variant:ident => $str:expr),* }) => {
#[derive(PartialEq, PartialOrd, Copy, Clone, Eq, Ord, Hash, Debug)]
pub enum $enum_name {
$(
#[doc=$str]
$variant,
)*
}
impl ::std::fmt::Display for $enum_name {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
fmt.write_str(self.as_ref())
}
}
impl AsRef<str> for $enum_name {
fn as_ref(&self) -> &str {
use $enum_name::*;
match *self {
$(
$variant => $str,
)*
}
}
}
impl ::std::str::FromStr for $enum_name {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use $enum_name::*;
match s {
$(
$str => Ok($variant),
)*
_ => Err("oh noes".into()),
}
}
}
}
}
enum_with_str_repr!{
HttpVersion {
Http09 => "HTTP/0.9",
Http10 => "HTTP/1.0",
Http11 => "HTTP/1.1",
Http20 => "HTTP/2.0"
}
}
fn main() {
let version: HttpVersion = "HTTP/0.9".parse().unwrap();
println!("version {}", version);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment