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!
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"),
28 You can match multiple patterns with `|`:
34 1 | 2 => println!("one or two"),
35 3 => println!("three"),
36 _ => println!("anything"),
40 This prints `one or two`.
44 You can match a range of values with `...`:
50 1 ... 5 => println!("one through five"),
51 _ => println!("anything"),
55 This prints `one through five`.
57 Ranges are mostly used with integers and `char`s:
63 'a' ... 'j' => println!("early letter"),
64 'k' ... 'z' => println!("late letter"),
65 _ => println!("something else"),
69 This prints `something else`.
73 You can bind values to names with `@`:
79 e @ 1 ... 5 => println!("got a range element {}", e),
80 _ => println!("anything"),
84 This prints `got a range element 1`. This is useful when you want to
85 do a complicated match of part of a data structure:
93 let name = "Steve".to_string();
94 let mut x: Option<Person> = Some(Person { name: Some(name) });
96 Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
101 This prints `Some("Steve")`: We’ve bound the inner `name` to `a`.
103 If you use `@` with `|`, you need to make sure the name is bound in each part
110 e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
111 _ => println!("anything"),
117 You can use `_` in a pattern to disregard the type and value.
118 For example, here’s a `match` against a `Result<T, E>`:
121 # let some_value: Result<i32, &'static str> = Err("There was an error");
123 Ok(value) => println!("got a value: {}", value),
124 Err(_) => println!("an error occurred"),
128 In the first arm, we bind the value inside the `Ok` variant to `value`. But
129 in the `Err` arm, we use `_` to disregard the specific error, and just print
130 a general error message.
132 `_` is valid in any pattern that creates a binding. This can be useful to
133 ignore parts of a larger structure:
136 fn coordinate() -> (i32, i32, i32) {
137 // generate and return some sort of triple tuple
141 let (x, _, z) = coordinate();
144 Here, we bind the first and last element of the tuple to `x` and `z`, but
145 ignore the middle element.
147 Similarly, you can use `..` in a pattern to disregard multiple values.
151 Value(i32, i32, i32),
155 let x = OptionalTuple::Value(5, -2, 3);
158 OptionalTuple::Value(..) => println!("Got a tuple!"),
159 OptionalTuple::Missing => println!("No such luck."),
163 This prints `Got a tuple!`.
167 You can introduce ‘match guards’ with `if`:
175 let x = OptionalInt::Value(5);
178 OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
179 OptionalInt::Value(..) => println!("Got an int!"),
180 OptionalInt::Missing => println!("No such luck."),
184 This prints `Got an int!`.
186 If you’re using `if` with multiple patterns, the `if` applies to both sides:
193 4 | 5 if y => println!("yes"),
198 This prints `no`, because the `if` applies to the whole of `4 | 5`, and not to
199 just the `5`, In other words, the the precedence of `if` behaves like this:
213 If you want to get a [reference][ref], use the `ref` keyword:
219 ref r => println!("Got a reference to {}", r),
223 This prints `Got a reference to 5`.
225 [ref]: references-and-borrowing.html
227 Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref`
228 keyword _creates_ a reference, for use in the pattern. If you need a mutable
229 reference, `ref mut` will work in the same way:
235 ref mut mr => println!("Got a mutable reference to {}", mr),
241 If you have a compound data type, like a [`struct`][struct], you can destructure it
250 let origin = Point { x: 0, y: 0 };
253 Point { x, y } => println!("({},{})", x, y),
257 [struct]: structs.html
259 We can use `:` to give a value a different name.
267 let origin = Point { x: 0, y: 0 };
270 Point { x: x1, y: y1 } => println!("({},{})", x1, y1),
274 If we only care about some of the values, we don’t have to give them all names:
282 let origin = Point { x: 0, y: 0 };
285 Point { x, .. } => println!("x is {}", x),
289 This prints `x is 0`.
291 You can do this kind of match on any member, not just the first:
299 let origin = Point { x: 0, y: 0 };
302 Point { y, .. } => println!("y is {}", y),
306 This prints `y is 0`.
308 This ‘destructuring’ behavior works on any compound data type, like
309 [tuples][tuples] or [enums][enums].
311 [tuples]: primitive-types.html#tuples
316 Whew! That’s a lot of different ways to match things, and they can all be
317 mixed and matched, depending on what you’re doing:
321 Foo { x: Some(ref name), y: None } => ...
325 Patterns are very powerful. Make good use of them.