如何在匹配期间访问枚举变体的字段而不显式绑定它?

lef*_*ead 8 rust

假设我有一个 enum E,它可能是自动生成的或不受我控制的,有许多变体,每个变体都有许多字段。

enum E {
    A {
        x1: u8,
        x2: u8,
        x3: u8,
        // ...
        x9: u8,
    },
    B,
}
Run Code Online (Sandbox Code Playgroud)

实际上,这些字段可能更长,既不便于记忆,也不便于打字。

我现在想编写对 (variants of) 进行操作的函数E。但是,我也很懒惰,我不想重复自己,在解构 enum* 时显式声明每个使用的字段

直觉上,我希望绑定运算符@在这里完成这项工作,但它只绑定整个 enum e,而不是给定的 variant E::A

实现以下意图的最短/最优雅的方法是什么?

fn f(e: &E) {
    match e {
        bad @ E::A { .. } => dbg!(bad.x1),
        _ => {}
    }
}
Run Code Online (Sandbox Code Playgroud)

*更新,因为这已经被带到了两个答案了,我也没有想匹配E::A { x1, .. },因为这需要具有长名称的多个字段时变得乏味。在下面的示例中,我必须some_other_field_with_an_impossibly_long_name在自己的代码中输入两次(一次是在绑定时,一次是在使用时),而在假设的bad @ E::A情况下,我只需要输入一次。

match e {
    E::A { some_field_with_a_long_name, some_other_field_with_an_impossibly_long_name, yet_another_field, .. } => dbg!(some_other_field_with_an_impossibly_long_name),
    _ => {}
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*onA 1

我认为以下内容可能会有所帮助:

fn f(e: &E) {
  match e {
   E::A {x1, .. } => {dbg!(x1);},
    _ => {}
  };
}
Run Code Online (Sandbox Code Playgroud)

E::A {x1,..}是 的缩写bad @ E::A {x1:x1, ..},并将其值绑定到主体作用域中可用的bad.x1新局部变量。x1