Match enum variant data

Is it possible to match all enum variants that have a value?

For example:

enum Example {
  variant1(i32),
  variant2(i32),
  variant3(i32),
}

match example {
  _(value) => println!("{}", value);
}

Not without spelling it out.

match example {
  // n.b. possible as a single match block here as they're all the same type
  variant1(value) | variant2(value) | variant3(value) => println!("{}", value),
}

Well that's the solution i know. But i thought there might be an easier way

If your enum variants have repetitive structure and you find it inconvenient to access, maybe you should factor out said repetitive structure in a struct, along with a "kind" enum which has no associated data. Then you can unconditionally operate on the former associated data directly through the struct, and only check the kind enum when it's relevant.

You can write a function for this, so that you only have to write it once:

impl AsRef<i32> for Example {
    fn as_ref(&self)->&i32 {
        match self {
            // n.b. possible as a single match block here as they're all the same type
            variant1(value) | variant2(value) | variant3(value) => value,
        }
    }
}

(untested)

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.