如何在匹配中匹配枚举变体

kyk*_*yku 9 rust

@ 运算符或其他解决方案是否有一个位置可以将匹配臂中的变量绑定到变体类型而不是整个枚举?在以下示例中,所有barbazqux的类型均为 Foo,而不是 Foo::Bar、Foo::Baz、Foo::Qux,并且示例无法编译。

enum Foo {
   Bar(i32),
   Baz{s: String},
   Qux,
}

fn main() {
  let foo = Foo::Bar(42);

  match foo {
    bar @ Bar(..) => bar.0.to_string(),
    baz @ Baz{..} => baz.s,
    qux @ Qux => "".to_owned(),
  }
}

Run Code Online (Sandbox Code Playgroud)

eff*_*ect 1

我认为您正在寻找的语法是这样的?

enum Foo {
   Bar(i32),
   Baz{s: String},
   Qux,
}

fn main() {
  let foo = Foo::Bar(42);

  let s = match foo {
    Foo::Bar(bar) => bar.to_string(),
    Foo::Baz{s} => s,
    Foo::Qux => "".to_owned(),
  };
  
  dbg!(s);
}
Run Code Online (Sandbox Code Playgroud)