Rust: Proper way to repeat the same action over multiple match cases of an enum?

  Kiến thức lập trình

I have a slightly more complex enum with the same set of actions taken for multiple of the possible options, e.g. something like

enum Select {
    option1,
    option2,
    option3,
    option4,
    option5,
}

fn a() {
    // do something
}

fn b() {
    // do something else
}

fn c() {
    // do some third thing
}

fn test(Select: selection) {
    match selection {
        Select::option1 => {
            a();
        },
        Select::option2 => {
            a();
            b();
        },
        Select::option3 => {
            a();
            c();
        },
        Select::option4 => {
            b();
            c();
        },
        Select::option5 => {},
    }
}

Instead of repeating the same statement multiple times for different options, is there an option to write every statement only once and choosing which options it should be run for? I.e. something like:

do a() if selection matches option1 or option2 or option3
do b() if selection matches option2 or option4
do c() if selection matches option3 or option4

I guess I could do multiple match statements with defaults, but is that considered proper style or is there some better way?

LEAVE A COMMENT