Is there a way to evaluate a function as the input to a match arm?

Viewed 294
match input_string {
    func_that_returns_string(MyEnum::MyVariant1) => do_something(),
    func_that_returns_string(MyEnum::MyVariant2) => do_something_else(),
    _=> do_nothing(),
}

Here is an examples of the error message: Error: expected tuple struct or tuple variant, found function func_that_returns_string

1 Answers

Well, you can do it using a match guard, which looks like x if condition =>

fn fun(variant: MyEnum) -> String {
    match variant {
        MyEnum::Variant1 => "String1".to_string(),
        MyEnum::Variant2 => "String2".to_string(),
    }
}

pub fn main() {
    let s = "String2".to_string();
    match s {
        s if s == fun(MyEnum::Variant1) => do_something(1),
        s if s == fun(MyEnum::Variant2) => do_something(2),
        _ => {},
    }

    // prints 2
}

But either way it looks clumsy and I suggest you to revise your design.

Related