]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/flow_control/match/binding.md
New upstream version 1.45.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / flow_control / match / binding.md
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() {
14 println!("Tell me what type of person you are");
15
16 match age() {
17 0 => println!("I haven't celebrated my first birthday yet"),
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.
21 n @ 1 ..= 12 => println!("I'm a child of age {:?}", n),
22 n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n),
23 // Nothing bound. Return the result.
24 n => println!("I'm an old person of age {:?}", n),
25 }
26 }
27 ```
28
29 You can also use binding to "destructure" `enum` variants, such as `Option`:
30
31 ```rust,editable
32 fn some_number() -> Option<u32> {
33 Some(42)
34 }
35
36 fn main() {
37 match some_number() {
38 // Got `Some` variant, match if its value, bound to `n`,
39 // is equal to 42.
40 Some(n @ 42) => println!("The Answer: {}!", n),
41 // Match any other number.
42 Some(n) => println!("Not interesting... {}", n),
43 // Match anything else (`None` variant).
44 _ => (),
45 }
46 }
47 ```
48
49 ### See also:
50 [`functions`][functions], [`enums`][enums] and [`Option`][option]
51
52 [functions]: ../../fn.md
53 [enums]: ../../custom_types/enum.md
54 [option]: ../../std/option.md