Implement Display for Enum

I have an enum that I need to map to strings:

enum Visibility {
    Hidden,
    AfterDueDate,
    AfterPublished,
    Visible, // default
}

impl fmt::Display for Visibility {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let printable = match *self {
            Visibility::Hidden => "hidden",
            Visibility::AfterDueDate => "after_due_date",
            Visibility::AfterPublished => "after_published",
            Visibility::Visible => "visible",
        };
        write!(f, "{:?}", printable)
    }
}

Surely there is some programmatic way to do this?

Do they have to be in snake_case? Because the default #[derive(Debug)] does the name of the variant for you by default:

#[derive(Debug)]
enum Foo {
    Bar
}
println!("{:?}", Foo::Bar);
//Prints Bar

I usually just make an as_str method and put that match in it. Then every time I need the string, I call that. I don't think it's too bad of a solution.

strum::Display

3 Likes