0
votes

I'm just learning and writing a small poker program with the following code:

enum Action {
    Fold,
    Check,
    Call(i32),
    Bet(i32),
    Raise(i32),
    Post(i32),
}

// ...

infors[seat] = match action {
    Action::Fold => Status::Out,
    Action::Check => infors[seat],
    Action::Call(x) => infors[seat].incr(x),
    Action::Bet(x) => infors[seat].incr(x),       
    Action::Raise(x) => infors[seat].incr(x),
    Action::Post(x) => infors[seat].incr(x),
};

Is there a way to pattern match on all variants with the i32 field so that the final 4 lines can be combined, since they all do the same thing with x?

Something in the spirit of

Action::_(x) => // ...
1

1 Answers

2
votes

You can do something like this:

match action {
    Action::Fold => Status::Out,
    Action::Check => infors[seat],
    Action::Call(x) | Action::Bet(x) | Action::Raise(x) | Action::Post(x) => infors[seat].incr(x),
}

And if you want to shorten everything, you can use Action::*

{
    // Only import in this block to avoid name conflicts
    use Action::*;
    match action {
        Fold => Status::Out,
        Check => infors[seat],
        Call(x) | Bet(x) | Raise(x) | Post(x) => infors[seat].incr(x),
    }
}

Rust Playground

Read the Rust Book Pattern Syntax Chapter for more information