]> git.proxmox.com Git - rustc.git/blob - src/doc/trpl/patterns.md
Imported Upstream version 1.5.0+dfsg1
[rustc.git] / src / doc / trpl / patterns.md
1 % Patterns
2
3 Patterns are quite common in Rust. We use them in [variable
4 bindings][bindings], [match statements][match], and other places, too. Let’s go
5 on a whirlwind tour of all of the things patterns can do!
6
7 [bindings]: variable-bindings.html
8 [match]: match.html
9
10 A quick refresher: you can match against literals directly, and `_` acts as an
11 ‘any’ case:
12
13 ```rust
14 let x = 1;
15
16 match x {
17 1 => println!("one"),
18 2 => println!("two"),
19 3 => println!("three"),
20 _ => println!("anything"),
21 }
22 ```
23
24 This prints `one`.
25
26 There’s one pitfall with patterns: like anything that introduces a new binding,
27 they introduce shadowing. For example:
28
29 ```rust
30 let x = 'x';
31 let c = 'c';
32
33 match c {
34 x => println!("x: {} c: {}", x, c),
35 }
36
37 println!("x: {}", x)
38 ```
39
40 This prints:
41
42 ```text
43 x: c c: c
44 x: x
45 ```
46
47 In other words, `x =>` matches the pattern and introduces a new binding named
48 `x` that’s in scope for the match arm. Because we already have a binding named
49 `x`, this new `x` shadows it.
50
51 # Multiple patterns
52
53 You can match multiple patterns with `|`:
54
55 ```rust
56 let x = 1;
57
58 match x {
59 1 | 2 => println!("one or two"),
60 3 => println!("three"),
61 _ => println!("anything"),
62 }
63 ```
64
65 This prints `one or two`.
66
67 # Destructuring
68
69 If you have a compound data type, like a [`struct`][struct], you can destructure it
70 inside of a pattern:
71
72 ```rust
73 struct Point {
74 x: i32,
75 y: i32,
76 }
77
78 let origin = Point { x: 0, y: 0 };
79
80 match origin {
81 Point { x, y } => println!("({},{})", x, y),
82 }
83 ```
84
85 [struct]: structs.html
86
87 We can use `:` to give a value a different name.
88
89 ```rust
90 struct Point {
91 x: i32,
92 y: i32,
93 }
94
95 let origin = Point { x: 0, y: 0 };
96
97 match origin {
98 Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
99 }
100 ```
101
102 If we only care about some of the values, we don’t have to give them all names:
103
104 ```rust
105 struct Point {
106 x: i32,
107 y: i32,
108 }
109
110 let origin = Point { x: 0, y: 0 };
111
112 match origin {
113 Point { x, .. } => println!("x is {}", x),
114 }
115 ```
116
117 This prints `x is 0`.
118
119 You can do this kind of match on any member, not just the first:
120
121 ```rust
122 struct Point {
123 x: i32,
124 y: i32,
125 }
126
127 let origin = Point { x: 0, y: 0 };
128
129 match origin {
130 Point { y, .. } => println!("y is {}", y),
131 }
132 ```
133
134 This prints `y is 0`.
135
136 This ‘destructuring’ behavior works on any compound data type, like
137 [tuples][tuples] or [enums][enums].
138
139 [tuples]: primitive-types.html#tuples
140 [enums]: enums.html
141
142 # Ignoring bindings
143
144 You can use `_` in a pattern to disregard the type and value.
145 For example, here’s a `match` against a `Result<T, E>`:
146
147 ```rust
148 # let some_value: Result<i32, &'static str> = Err("There was an error");
149 match some_value {
150 Ok(value) => println!("got a value: {}", value),
151 Err(_) => println!("an error occurred"),
152 }
153 ```
154
155 In the first arm, we bind the value inside the `Ok` variant to `value`. But
156 in the `Err` arm, we use `_` to disregard the specific error, and just print
157 a general error message.
158
159 `_` is valid in any pattern that creates a binding. This can be useful to
160 ignore parts of a larger structure:
161
162 ```rust
163 fn coordinate() -> (i32, i32, i32) {
164 // generate and return some sort of triple tuple
165 # (1, 2, 3)
166 }
167
168 let (x, _, z) = coordinate();
169 ```
170
171 Here, we bind the first and last element of the tuple to `x` and `z`, but
172 ignore the middle element.
173
174 Similarly, you can use `..` in a pattern to disregard multiple values.
175
176 ```rust
177 enum OptionalTuple {
178 Value(i32, i32, i32),
179 Missing,
180 }
181
182 let x = OptionalTuple::Value(5, -2, 3);
183
184 match x {
185 OptionalTuple::Value(..) => println!("Got a tuple!"),
186 OptionalTuple::Missing => println!("No such luck."),
187 }
188 ```
189
190 This prints `Got a tuple!`.
191
192 # ref and ref mut
193
194 If you want to get a [reference][ref], use the `ref` keyword:
195
196 ```rust
197 let x = 5;
198
199 match x {
200 ref r => println!("Got a reference to {}", r),
201 }
202 ```
203
204 This prints `Got a reference to 5`.
205
206 [ref]: references-and-borrowing.html
207
208 Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref`
209 keyword _creates_ a reference, for use in the pattern. If you need a mutable
210 reference, `ref mut` will work in the same way:
211
212 ```rust
213 let mut x = 5;
214
215 match x {
216 ref mut mr => println!("Got a mutable reference to {}", mr),
217 }
218 ```
219
220 # Ranges
221
222 You can match a range of values with `...`:
223
224 ```rust
225 let x = 1;
226
227 match x {
228 1 ... 5 => println!("one through five"),
229 _ => println!("anything"),
230 }
231 ```
232
233 This prints `one through five`.
234
235 Ranges are mostly used with integers and `char`s:
236
237 ```rust
238 let x = '💅';
239
240 match x {
241 'a' ... 'j' => println!("early letter"),
242 'k' ... 'z' => println!("late letter"),
243 _ => println!("something else"),
244 }
245 ```
246
247 This prints `something else`.
248
249 # Bindings
250
251 You can bind values to names with `@`:
252
253 ```rust
254 let x = 1;
255
256 match x {
257 e @ 1 ... 5 => println!("got a range element {}", e),
258 _ => println!("anything"),
259 }
260 ```
261
262 This prints `got a range element 1`. This is useful when you want to
263 do a complicated match of part of a data structure:
264
265 ```rust
266 #[derive(Debug)]
267 struct Person {
268 name: Option<String>,
269 }
270
271 let name = "Steve".to_string();
272 let mut x: Option<Person> = Some(Person { name: Some(name) });
273 match x {
274 Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
275 _ => {}
276 }
277 ```
278
279 This prints `Some("Steve")`: we’ve bound the inner `name` to `a`.
280
281 If you use `@` with `|`, you need to make sure the name is bound in each part
282 of the pattern:
283
284 ```rust
285 let x = 5;
286
287 match x {
288 e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
289 _ => println!("anything"),
290 }
291 ```
292
293 # Guards
294
295 You can introduce ‘match guards’ with `if`:
296
297 ```rust
298 enum OptionalInt {
299 Value(i32),
300 Missing,
301 }
302
303 let x = OptionalInt::Value(5);
304
305 match x {
306 OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
307 OptionalInt::Value(..) => println!("Got an int!"),
308 OptionalInt::Missing => println!("No such luck."),
309 }
310 ```
311
312 This prints `Got an int!`.
313
314 If you’re using `if` with multiple patterns, the `if` applies to both sides:
315
316 ```rust
317 let x = 4;
318 let y = false;
319
320 match x {
321 4 | 5 if y => println!("yes"),
322 _ => println!("no"),
323 }
324 ```
325
326 This prints `no`, because the `if` applies to the whole of `4 | 5`, and not to
327 just the `5`. In other words, the precedence of `if` behaves like this:
328
329 ```text
330 (4 | 5) if y => ...
331 ```
332
333 not this:
334
335 ```text
336 4 | (5 if y) => ...
337 ```
338
339 # Mix and Match
340
341 Whew! That’s a lot of different ways to match things, and they can all be
342 mixed and matched, depending on what you’re doing:
343
344 ```rust,ignore
345 match x {
346 Foo { x: Some(ref name), y: None } => ...
347 }
348 ```
349
350 Patterns are very powerful. Make good use of them.