Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I match on all enum variants that have the same shape of their values?

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?

like image 991
milck Avatar asked Jan 24 '26 15:01

milck


1 Answers

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`
}
like image 65
Shepmaster Avatar answered Jan 27 '26 06:01

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!