绑定
在 match 中,若间接地访问一个变量,则不经过重新绑定就无法在分支中再使用它。match
提供了 @ 符号来绑定变量到名称:
1. // `age` 函数,返回一个 `u32` 值。
2. fn age() -> u32 {
3. 15
4. }
6. fn main() {
7. println!("Tell me type of person you are");
9. match age() {
10. 0 => println!("I'm not born yet I guess"),
11. // 可以直接 `match` 1 ..= 12,但怎么把岁数打印出来呢?
12. // 相反,在 1 ..= 12 分支中绑定匹配值到 `n` 。现在年龄就可以读取了。
13. n @ 1 ..= 12 => println!("I'm a child of age {:?}", n),
14. n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n),
15. // 不符合上面的范围。返回结果。
16. n => println!("I'm an old person of age {:?}", n),
17. }
18. }
你也可以使用绑定来“结构” enum 变体,例如 Option:
1. fn some_number() -> Option<u32> {
2. Some(42)
3. }
5. fn main() {
6. match some_number() {
7. // Got `Some` variant, match if its value, bound to `n`,
8. // is equal to 42.
9. Some(n @ 42) => println!("The Answer: {}!", n),
10. // Match any other number.
11. Some(n) => println!("Not interesting... {}", n),
12. // Match anything else (`None` variant).
13. _ => (),
14. }
15. }
