File tree 1 file changed +31
-3
lines changed
1 file changed +31
-3
lines changed Original file line number Diff line number Diff line change @@ -70,8 +70,7 @@ This prints `something else`
70
70
71
71
# Bindings
72
72
73
- If you’re matching multiple things, via a ` | ` or a ` ... ` , you can bind
74
- the value to a name with ` @ ` :
73
+ You can bind values to names with ` @ ` :
75
74
76
75
``` rust
77
76
let x = 1 ;
@@ -82,7 +81,36 @@ match x {
82
81
}
83
82
```
84
83
85
- This prints ` got a range element 1 ` .
84
+ This prints ` got a range element 1 ` . This is useful when you want to
85
+ do a complicated match of part of a data structure:
86
+
87
+ ``` rust
88
+ #[derive(Debug )]
89
+ struct Person {
90
+ name : Option <String >,
91
+ }
92
+
93
+ let name = " Steve" . to_string ();
94
+ let mut x : Option <Person > = Some (Person { name : Some (name ) });
95
+ match x {
96
+ Some (Person { name : ref a @ Some (_ ), .. }) => println! (" {:?}" , a ),
97
+ _ => {}
98
+ }
99
+ ```
100
+
101
+ This prints ` Some("Steve") ` : We’ve bound the inner ` name ` to ` a ` .
102
+
103
+ If you use ` @ ` with ` | ` , you need to make sure the name is bound in each part
104
+ of the pattern:
105
+
106
+ ``` rust
107
+ let x = 5 ;
108
+
109
+ match x {
110
+ e @ 1 ... 5 | e @ 8 ... 10 => println! (" got a range element {}" , e ),
111
+ _ => println! (" anything" ),
112
+ }
113
+ ```
86
114
87
115
# Ignoring variants
88
116
You can’t perform that action at this time.
0 commit comments