使用多个匹配时是否有更简单的方法来绑定整个匹配?

hel*_*low 5 syntax pattern-matching rust

将变量绑定到匹配表达式可以通过使用@和变量名来完成,例如:

#[derive(Debug)]
enum Foo {
    First,
    Second,
    Third,
    Fourth,
}

fn bar(f: Foo) {
    match f {
        e @ Foo::First => println!("{:?}", e),
        _ => {}
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要绑定e多个匹配项,则必须对每种可能性重复绑定.

fn bar(f: Foo) {
    match f {
        e @ Foo::First | e @ Foo::Second | e @ Foo::Fourth => println!("{:?}", e),
        _ => {}
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法呢?

Joe*_*lay 7

在 Rust 1.53 及更高版本中,您可以像这样嵌套“或”模式:

fn bar(f: Foo) {
    match f {
        e @ (Foo::First | Foo::Second | Foo::Fourth) => println!("{:?}", e),
        _ => {}
    }
}
Run Code Online (Sandbox Code Playgroud)