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 There’s one pitfall with patterns: like anything that introduces a new binding,
27 they introduce shadowing. For example:
34 x => println!("x: {} c: {}", x, c),
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
55 You can match multiple patterns with `|`:
61 1 | 2 => println!("one or two"),
62 3 => println!("three"),
63 _ => println!("anything"),
67 This prints `one or two`.
71 If you have a compound data type, like a [`struct`][struct], you can destructure it
80 let origin = Point { x: 0, y: 0 };
83 Point { x, y } => println!("({},{})", x, y),
87 [struct]: structs.html
89 We can use `:` to give a value a different name.
97 let origin = Point { x: 0, y: 0 };
100 Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
104 If we only care about some of the values, we don’t have to give them all names:
112 let origin = Point { x: 0, y: 0 };
115 Point { x, .. } => println!("x is {}", x),
119 This prints `x is 0`.
121 You can do this kind of match on any member, not only the first:
129 let origin = Point { x: 0, y: 0 };
132 Point { y, .. } => println!("y is {}", y),
136 This prints `y is 0`.
138 This ‘destructuring’ behavior works on any compound data type, like
139 [tuples][tuples] or [enums][enums].
141 [tuples]: primitive-types.html#tuples
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>`:
150 # let some_value: Result<i32, &'static str> = Err("There was an error");
152 Ok(value) => println!("got a value: {}", value),
153 Err(_) => println!("an error occurred"),
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.
161 `_` is valid in any pattern that creates a binding. This can be useful to
162 ignore parts of a larger structure:
165 fn coordinate() -> (i32, i32, i32) {
166 // generate and return some sort of triple tuple
170 let (x, _, z) = coordinate();
173 Here, we bind the first and last element of the tuple to `x` and `z`, but
174 ignore the middle element.
176 It’s worth noting that using `_` never binds the value in the first place,
177 which means a value may not move:
180 let tuple: (u32, String) = (5, String::from("five"));
182 // Here, tuple is moved, because the String moved:
185 // The next line would give "error: use of partially moved value: `tuple`"
186 // println!("Tuple is: {:?}", tuple);
190 let tuple = (5, String::from("five"));
192 // Here, tuple is _not_ moved, as the String was never moved, and u32 is Copy:
195 // That means this works:
196 println!("Tuple is: {:?}", tuple);
199 This also means that any temporary variables will be dropped at the end of the
203 // Here, the String created will be dropped immediately, as it’s not bound:
205 let _ = String::from(" hello ").trim();
208 You can also use `..` in a pattern to disregard multiple values:
212 Value(i32, i32, i32),
216 let x = OptionalTuple::Value(5, -2, 3);
219 OptionalTuple::Value(..) => println!("Got a tuple!"),
220 OptionalTuple::Missing => println!("No such luck."),
224 This prints `Got a tuple!`.
228 If you want to get a [reference][ref], use the `ref` keyword:
234 ref r => println!("Got a reference to {}", r),
238 This prints `Got a reference to 5`.
240 [ref]: references-and-borrowing.html
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:
250 ref mut mr => println!("Got a mutable reference to {}", mr),
256 You can match a range of values with `...`:
262 1 ... 5 => println!("one through five"),
263 _ => println!("anything"),
267 This prints `one through five`.
269 Ranges are mostly used with integers and `char`s:
275 'a' ... 'j' => println!("early letter"),
276 'k' ... 'z' => println!("late letter"),
277 _ => println!("something else"),
281 This prints `something else`.
285 You can bind values to names with `@`:
291 e @ 1 ... 5 => println!("got a range element {}", e),
292 _ => println!("anything"),
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:
302 name: Option<String>,
305 let name = "Steve".to_string();
306 let x: Option<Person> = Some(Person { name: Some(name) });
308 Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
313 This prints `Some("Steve")`: we’ve bound the inner `name` to `a`.
315 If you use `@` with `|`, you need to make sure the name is bound in each part
322 e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
323 _ => println!("anything"),
329 You can introduce ‘match guards’ with `if`:
337 let x = OptionalInt::Value(5);
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."),
346 This prints `Got an int!`.
348 If you’re using `if` with multiple patterns, the `if` applies to both sides:
355 4 | 5 if y => println!("yes"),
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:
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:
380 Foo { x: Some(ref name), y: None } => ...
384 Patterns are very powerful. Make good use of them.