Syntactic Suger for matching every enum variant

I have a rather large enum with about 20 variants. And some of those variants are nested.
But I can't just use a HashMap, Because I need to execute code for each variant, Not just provide output.

Is there a way to match all of the variants without this not so sugery looking code block:

match enum x {...}
     stopcomingupwithargh=> {},
     yetanotherargh=> {},

If all the matches do the same thing, then yes - a variable (including the anonymous variable _, which acts as a wildcard) in a match expression matches any value that may appear there. For example:

match x {
  X::CaseOne => special_case(),
  _ => everything_else(),

The _ arm will match anything not consumed by a preceding arm, so only X::CaseOne is handled by special_case() and all other variants are handled by everything_else().

If several arms share behaviour, then there's also a way to match several variants at once:

match x {
    X::CaseOne => special_case(),
    X::CaseTwo | X::CaseThree => common_case(),
    // more cases here…

If the arms all differ, then you have to write them out. You may still be able to extract common behaviours into helper functions, however.

For a more complete breakdown, including range matches and a few other esoteric options, see the Rust Reference.


If all variants hold the same data type or implement the same trait, then:

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.