]>
Commit | Line | Data |
---|---|---|
9346a6ac AL |
1 | % Slice patterns |
2 | ||
3 | If you want to match against a slice or array, you can use `&` with the | |
4 | `slice_patterns` feature: | |
5 | ||
6 | ```rust | |
7 | #![feature(slice_patterns)] | |
8 | ||
9 | fn main() { | |
10 | let v = vec!["match_this", "1"]; | |
11 | ||
12 | match &v[..] { | |
13 | ["match_this", second] => println!("The second element is {}", second), | |
14 | _ => {}, | |
15 | } | |
16 | } | |
17 | ``` | |
18 | ||
bd371182 AL |
19 | The `advanced_slice_patterns` gate lets you use `..` to indicate any number of |
20 | elements inside a pattern matching a slice. This wildcard can only be used once | |
21 | for a given array. If there's an identifier before the `..`, the result of the | |
22 | slice will be bound to that name. For example: | |
23 | ||
24 | ```rust | |
25 | #![feature(advanced_slice_patterns, slice_patterns)] | |
26 | ||
27 | fn is_symmetric(list: &[u32]) -> bool { | |
28 | match list { | |
29 | [] | [_] => true, | |
30 | [x, inside.., y] if x == y => is_symmetric(inside), | |
31 | _ => false | |
32 | } | |
33 | } | |
34 | ||
35 | fn main() { | |
36 | let sym = &[0, 1, 4, 2, 4, 1, 0]; | |
37 | assert!(is_symmetric(sym)); | |
38 | ||
39 | let not_sym = &[0, 1, 7, 2, 4, 1, 0]; | |
40 | assert!(!is_symmetric(not_sym)); | |
41 | } | |
42 | ``` |