Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 832
ewoolsey Avatar asked Sep 14 '25 19:09

ewoolsey


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.

like image 152
Alexey Larionov Avatar answered Sep 17 '25 10:09

Alexey Larionov