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