]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # Binding |
2 | ||
3 | Indirectly accessing a variable makes it impossible to branch and use that | |
4 | variable without re-binding. `match` provides the `@` sigil for binding values to | |
5 | names: | |
6 | ||
7 | ```rust,editable | |
8 | // A function `age` which returns a `u32`. | |
9 | fn age() -> u32 { | |
10 | 15 | |
11 | } | |
12 | ||
13 | fn main() { | |
b7449926 | 14 | println!("Tell me what type of person you are"); |
2c00a5a8 XL |
15 | |
16 | match age() { | |
17 | 0 => println!("I'm not born yet I guess"), | |
18 | // Could `match` 1 ... 12 directly but then what age | |
19 | // would the child be? Instead, bind to `n` for the | |
20 | // sequence of 1 .. 12. Now the age can be reported. | |
416331ca XL |
21 | n @ 1 ..= 12 => println!("I'm a child of age {:?}", n), |
22 | n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n), | |
2c00a5a8 XL |
23 | // Nothing bound. Return the result. |
24 | n => println!("I'm an old person of age {:?}", n), | |
25 | } | |
26 | } | |
27 | ``` | |
28 | ||
29 | ### See also: | |
30 | [functions] | |
31 | ||
dc9dc135 | 32 | [functions]: ../../fn.md |