绑定

match 中,若间接地访问一个变量,则不经过重新绑定就无法在分支中再使用它。match 提供了 @ 符号来绑定变量到名称:

  1. // `age` 函数,返回一个 `u32` 值。
  2. fn age() -> u32 {
  3. 15
  4. }
  5. fn main() {
  6. println!("Tell me what type of person you are");
  7. match age() {
  8. 0 => println!("I haven't celebrated my first birthday yet"),
  9. // 可以直接匹配(`match`) 1 ..= 12,但那样的话孩子会是几岁?
  10. // 相反,在 1 ..= 12 分支中绑定匹配值到 `n` 。现在年龄就可以读取了。
  11. n @ 1 ..= 12 => println!("I'm a child of age {:?}", n),
  12. n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n),
  13. // 不符合上面的范围。返回结果。
  14. n => println!("I'm an old person of age {:?}", n),
  15. }
  16. }

你也可以使用绑定来“解构” enum 变体,例如 Option:

  1. fn some_number() -> Option<u32> {
  2. Some(42)
  3. }
  4. fn main() {
  5. match some_number() {
  6. // 得到 `Some` 可变类型,如果它的值(绑定到 `n` 上)等于 42,则匹配。
  7. Some(n @ 42) => println!("The Answer: {}!", n),
  8. // 匹配任意其他数字。
  9. Some(n) => println!("Not interesting... {}", n),
  10. // 匹配任意其他值(`None` 可变类型)。
  11. _ => (),
  12. }
  13. }

参见:

函数枚举Option