Rust Reference ยท Patterns
Slice patterns
Reference for Rust slice patterns: matching arrays and slices by length and shape, [first, .., last], rest @ .. bindings, and recursion over slices.
A slice pattern matches an array, a slice or a Vec (through its slice) by its length and the values at certain positions. Square brackets hold one pattern per element, and a single .. can stand for "any number of elements here".
Because the length of a slice is only known at run time, slice patterns on &[T] are refutable: you need a catch-all arm. Patterns on fixed-size arrays [T; N] can be irrefutable if every element is matched.
match values {
[] => {}
[only] => {}
[first, .., last] => {}
}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
[a, b, c] // exactly three elements [first, ..] // at least one element [.., last] // at least one element [first, rest @ ..] // rest binds a subslice [a, .., b] // at least two [head, mid @ .., tail]
| Part | Description |
|---|---|
| Element patterns | Any pattern: literals, ranges, identifiers, nested structs. |
.. |
Matches zero or more elements. Allowed once per slice pattern. |
name @ .. |
Binds the skipped elements: &[T] when matching a slice by reference, [T; K] when matching an array by value. |
Errors and edge cases: a slice pattern against &[T] without a catch-all arm gives E0004 (non-exhaustive patterns). [a, b] against an array of length 3 is a compile error because lengths are checked statically for arrays. An empty [] and a [..] arm together are exhaustive for slices.
Usage notes
- Works through references. Matching
&[T]or&Vec<T>(viav.as_slice()) binds elements as references through default binding modes. - Vec directly. A
Vec<T>is not a slice: writematch v.as_slice() { ... }orv[..]. - Strings of arguments. Matching on
&[&str]is a neat way to parse small command lines, as in the example above. - Recursion warning.
[head, tail @ ..]recursion is clear but uses stack depth proportional to the length; prefer iterators for large inputs. - Constants and ranges work as element patterns:
[0, ..],[1..=9, rest @ ..]. - Byte strings.
b"GET"is&[u8; 3]; match input bytes with[b'G', b'E', b'T', ..]. - Slice patterns on
&mut [T]give mutable references to elements, handy for in-place algorithms.
Related
match, Destructuring,_and..patterns,[T]slices,[T; N]arrays- Lessons: Slices, Arrays, Patterns