Pattern Match enum

#1

Say I have an enum where most of the options have a value of the same type, but one or two don’t. I I’d like to format the enum by pattern matching all the options that have values… how do I do that? For example:

pub enum Error {
    SUCCESS,
    INVALID_PARAM(&'static str),
    NOT_FOUND(&'static str),
    BUSY(&'static str),
    OTHER(&'static str)
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::SUCCESS => write!(f, "SUCCESS"),
            Error::_(s) => write!(f, "{}", s),  // <- this doesn't work, but I'd like something like it
        }
    }
}

Is there a way to pattern match against all options of an enum that have the same type like this?

#2

You can actually just match against multiple variations of the enum as long as the parameters have the same name and type.
Playground

1 Like
#3

It’s not as nice as your example, but you can combine pattern arms into a single code block.

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::SUCCESS => write!(f, "SUCCESS"),
            Error::INVALID_PARAM(s) | Error::NOT_FOUND(s)
                | Error::BUSY(s) | Error::OTHER(s) => write!(f, "{}", s),
        }
    }
}
2 Likes
#4

@OptimisticPeach & @cuviper, yea I knew about that pattern match, was hoping for something more “complete”. Thanks!

#5

But if there was a “match all that have a single parameter” pattern, then what about the arms without matching types? Or what if there is more than one paremeter in the various arms in the enum?