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