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!
7 [bindings]: variable-bindings.html
10 A quick refresher: you can match against literals directly, and `_` acts as an
19 3 => println!("three"),
20 _ => println!("anything"),
26 It's possible to create a binding for the value in the any case:
32 y => println!("x: {} y: {}", x, y),
42 Note it is an error to have both a catch-all `_` and a catch-all binding in the same match block:
48 y => println!("x: {} y: {}", x, y),
49 _ => println!("anything"), // this causes an error as it is unreachable
53 There’s one pitfall with patterns: like anything that introduces a new binding,
54 they introduce shadowing. For example:
61 x => println!("x: {} c: {}", x, c),
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
82 You can match multiple patterns with `|`:
88 1 | 2 => println!("one or two"),
89 3 => println!("three"),
90 _ => println!("anything"),
94 This prints `one or two`.
98 If you have a compound data type, like a [`struct`][struct], you can destructure it
107 let origin = Point { x: 0, y: 0 };
110 Point { x, y } => println!("({},{})", x, y),
114 [struct]: structs.html
116 We can use `:` to give a value a different name.
124 let origin = Point { x: 0, y: 0 };
127 Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
131 If we only care about some of the values, we don’t have to give them all names:
139 let point = Point { x: 2, y: 3 };
142 Point { x, .. } => println!("x is {}", x),
146 This prints `x is 2`.
148 You can do this kind of match on any member, not only the first:
156 let point = Point { x: 2, y: 3 };
159 Point { y, .. } => println!("y is {}", y),
163 This prints `y is 3`.
165 This ‘destructuring’ behavior works on any compound data type, like
166 [tuples][tuples] or [enums][enums].
168 [tuples]: primitive-types.html#tuples
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>`:
177 # let some_value: Result<i32, &'static str> = Err("There was an error");
179 Ok(value) => println!("got a value: {}", value),
180 Err(_) => println!("an error occurred"),
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.
188 `_` is valid in any pattern that creates a binding. This can be useful to
189 ignore parts of a larger structure:
192 fn coordinate() -> (i32, i32, i32) {
193 // Generate and return some sort of triple tuple.
197 let (x, _, z) = coordinate();
200 Here, we bind the first and last element of the tuple to `x` and `z`, but
201 ignore the middle element.
203 It’s worth noting that using `_` never binds the value in the first place,
204 which means that the value does not move:
207 let tuple: (u32, String) = (5, String::from("five"));
209 // Here, tuple is moved, because the String moved:
212 // The next line would give "error: use of partially moved value: `tuple`".
213 // println!("Tuple is: {:?}", tuple);
217 let tuple = (5, String::from("five"));
219 // Here, tuple is _not_ moved, as the String was never moved, and u32 is Copy:
222 // That means this works:
223 println!("Tuple is: {:?}", tuple);
226 This also means that any temporary variables will be dropped at the end of the
230 // Here, the String created will be dropped immediately, as it’s not bound:
232 let _ = String::from(" hello ").trim();
235 You can also use `..` in a pattern to disregard multiple values:
239 Value(i32, i32, i32),
243 let x = OptionalTuple::Value(5, -2, 3);
246 OptionalTuple::Value(..) => println!("Got a tuple!"),
247 OptionalTuple::Missing => println!("No such luck."),
251 This prints `Got a tuple!`.
255 If you want to get a [reference][ref], use the `ref` keyword:
261 ref r => println!("Got a reference to {}", r),
265 This prints `Got a reference to 5`.
267 [ref]: references-and-borrowing.html
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:
277 ref mut mr => println!("Got a mutable reference to {}", mr),
283 You can match a range of values with `...`:
289 1 ... 5 => println!("one through five"),
290 _ => println!("anything"),
294 This prints `one through five`.
296 Ranges are mostly used with integers and `char`s:
302 'a' ... 'j' => println!("early letter"),
303 'k' ... 'z' => println!("late letter"),
304 _ => println!("something else"),
308 This prints `something else`.
312 You can bind values to names with `@`:
318 e @ 1 ... 5 => println!("got a range element {}", e),
319 _ => println!("anything"),
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:
329 name: Option<String>,
332 let name = "Steve".to_string();
333 let x: Option<Person> = Some(Person { name: Some(name) });
335 Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
340 This prints `Some("Steve")`: we’ve bound the inner `name` to `a`.
342 If you use `@` with `|`, you need to make sure the name is bound in each part
349 e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
350 _ => println!("anything"),
356 You can introduce ‘match guards’ with `if`:
364 let x = OptionalInt::Value(5);
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."),
373 This prints `Got an int!`.
375 If you’re using `if` with multiple patterns, the `if` applies to both sides:
382 4 | 5 if y => println!("yes"),
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:
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:
407 Foo { x: Some(ref name), y: None } => ...
411 Patterns are very powerful. Make good use of them.