在模式匹配的默认情况下,如何访问匹配值?

时间:2019-11-28 08:38:10

标签: rust

问题在于默认情况。

让我们考虑以下代码:

fn func(x: i64) {
  match x {
    0 => println!("Zero"),
    1 => println!("One"),
    _ => {
      //How to get the value here not via repeating the matched expression ?
    }
  };
}

1 个答案:

答案 0 :(得分:8)

假设您不想重复该表达式,因为它不仅比变量复杂,还可以将其绑定到变量:

fn func(x: i64) {
  match <some complex expression> {
    0 => println!("Zero"),
    1 => println!("One"),
    y => {
      // you can use y here
    }
  };
}

这也可以作为默认情况,因为变量模式就像_一样匹配所有内容。

_在您不想使用该值时非常有用。