I have an enum:
enum MyEnum {
A(i32),
B(i32),
C,
D,
// ...
}
Can I match on A and B simultaneously with something like this:
let a = MyEnum::A(1);
match a {
_(n) => { // do something for all variants which have one i32 value
}
_ => { // ignore the rest
}
};
Is there any way to accomplish this? Do I have to match all the variants and apply the same "body" for each?
No, your desired syntax is not possible; I don't know how that syntax could work if you had multiple variants with the same count of fields with differing types:
enum MyEnum {
A(bool),
B(String),
}
Do I have to match all the variants and apply the same "body" for each?
Yes, but you can use patterns to match them in a single match arm:
match a {
MyEnum::A(n) | MyEnum::B(n) => {
// use `n`
}
_ => {}
};
Or the equivalent if let:
if let MyEnum::A(n) | MyEnum::B(n) = a {
// use `n`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With