Sub topic 14
Matching on Slices and Arrays
This chapter assumes you can write a match on enums and tuples, and that you know the difference between [T; N], &[T], and Vec<T>. Slice patterns build on the destructuring you already used with tuples. The new part is that a slice's length is not known at compile time.
Array patterns and slice patterns
A pattern in square brackets describes a sequence. What the pattern can do depends on the type it is matched against.
- An array
[T; N]has a length that is part of its type. The compiler knows how many elements exist, so a pattern of the right length always matches. Such a pattern is irrefutable, and you can use it in a plainlet. - A slice
[T]has a length that is only known at run time. A pattern such as[a, b]matches only when the length is exactly 2. It is refutable, so you must handle the case where it fails.
fn main() {
let rgb: [u8; 3] = [255, 128, 0];
let [r, g, b] = rgb;
println!("{r} {g} {b}");
let [first, .., last] = [1, 2, 3, 4, 5];
println!("{first} {last}");
}Both let statements compile without an else branch because the array lengths are known. If you wrote let [a, b] = rgb;, the compiler would reject it with a length mismatch, since the array has three elements.
The rest pattern
The .. pattern stands for "any number of elements, including none". It can appear at most once in a slice pattern. You can bind the skipped elements by writing name @ ... The name then refers to a sub-slice (or, for an array, a smaller array).
| Pattern | Matches slices of length |
|---|---|
| `[]` | exactly 0 |
| `[x]` | exactly 1 |
| `[x, y]` | exactly 2 |
| `[first, ..]` | 1 or more |
| `[first, .., last]` | 2 or more |
| `[head, tail @ ..]` | 1 or more, `tail` is the rest |
| `[first, middle @ .., last]` | 2 or more, `middle` may be empty |
A recursive function shows the head, tail @ .. shape clearly:
fn sum(values: &[i32]) -> i32 {
match values {
[] => 0,
[head, tail @ ..] => head + sum(tail),
}
}
fn main() {
println!("{}", sum(&[1, 2, 3, 4]));
println!("{}", sum(&[]));
}Here values is a reference, so the bindings follow default binding modes. head is an &i32 and tail is an &[i32]. You do not write & or ref in the pattern.
Exhaustiveness
A match must cover every possible length. The compiler checks this for you. In the next example, the last arm covers every length of 2 or more, so the match is complete.
fn classify(values: &[i32]) -> String {
match values {
[] => "empty".to_string(),
[x] => format!("one element: {x}"),
[first, second] => format!("pair: {first}, {second}"),
[first, middle @ .., last] => {
format!("{first}..{last} with {} in between", middle.len())
}
}
}
fn main() {
println!("{}", classify(&[]));
println!("{}", classify(&[7]));
println!("{}", classify(&[1, 2]));
println!("{}", classify(&[1, 2, 3, 4, 5]));
}The pair arm comes before the general arm, so it handles length 2 first. If you delete the [] arm, the compiler reports a non-exhaustive match and names the missing pattern, &[]. This is a real benefit: you cannot forget the empty case.
Guards and literals
Elements can be matched against literals, ranges, or other patterns, and arms can have if guards. The next function parses a command line already split into words. It matches string literals at fixed positions and captures the rest:
fn run(args: &[&str]) -> String {
match args {
["hello"] => "hi".to_string(),
["hello", name] => format!("hi, {name}"),
["bye", rest @ ..] => format!("bye to {}", rest.join(" and ")),
[first, .., last] if first == last => {
format!("starts and ends with {first}")
}
_ => "unknown".to_string(),
}
}
fn main() {
println!("{}", run(&["hello"]));
println!("{}", run(&["hello", "Ada"]));
println!("{}", run(&["bye", "Ada", "Grace"]));
println!("{}", run(&["go", "far", "go"]));
println!("{}", run(&[]));
}The compiler does not reason about guards when it checks exhaustiveness. That is why the final _ arm is needed. Arms are tried from top to bottom, so put specific patterns before general ones.
Refutable patterns outside match
Because slice patterns can fail, the other pattern positions need a way to handle failure.
if letruns a block only when the pattern matches.let ... elsebinds names for the rest of the function, and theelseblock must diverge (return, break, panic).matches!returns abool.
fn describe_pair(values: &[i32]) -> String {
let [a, b] = values else {
return format!("not a pair ({} elements)", values.len());
};
format!("pair {a} and {b}")
}
fn swap_ends(values: &mut [i32]) {
if let [first, .., last] = values {
std::mem::swap(first, last);
}
}
fn main() {
println!("{}", describe_pair(&[1, 2]));
println!("{}", describe_pair(&[1, 2, 3]));
let mut data = [1, 2, 3, 4];
swap_ends(&mut data);
println!("{:?}", data);
let v = vec![9, 9];
println!("{}", matches!(v.as_slice(), [9, 9]));
}In swap_ends, the scrutinee is &mut [i32], so first and last are &mut i32. The two mutable borrows are legal because the pattern proves they point at different elements. You could not write this with two calls to values[0] and values[len - 1] in the same borrow, since the compiler cannot tell the indexes differ.
A Vec<i32> cannot be matched with slice patterns directly. Convert it first with as_slice() or &v[..].
Common errors
- Refutable pattern in a plain
let.let [a, b] = some_slice;fails with "refutable pattern in local binding". Addelse { ... }or useif let. - Two rest patterns.
[.., x, ..]is an error, because the compiler cannot decide wherexsits. Only one..is allowed. - Wrong array length.
let [a, b] = [1, 2, 3];is a compile-time mismatch, not a run-time failure. - Forgetting the types of bindings. Under a reference,
headis&T, notT. Use*heador rely on auto-deref in arithmetic and printing. - Matching a Vec. Patterns like
[a, b]do not apply toVec<T>. Usev.as_slice().
Exercise
Write fn middle_or_zero(values: &[i32]) -> i32 that returns the single middle element when the slice has exactly three elements, and 0 for any other length. Use one match with slice patterns, and no indexing.
Show answer
fn middleorzero(values: &[i32]) -> i32 {
match values {
[, mid, ] => *mid,
=> 0,
}
}
The pattern `[, mid, ] only matches length 3. mid is an &i32, so it is dereferenced. The ` arm covers all other lengths, including empty.