Sub topic 14
Matching on slices and arrays
This chapter assumes you know match, if let, references, and the difference between an array [T; N] and a slice &[T].
Why slice patterns
A slice has no length known at compile time. A slice pattern lets you check its length and pull out elements in one step, so you don't need len() checks and index arithmetic. The compiler also checks that your arms cover every possible length.
Matching a slice
fn describe(values: &[i32]) -> &'static str {
match values {
[] => "empty",
[_] => "one element",
[first, .., last] if first == last => "starts and ends the same",
[_, ..] => "many elements",
}
}
fn main() {
println!("{}", describe(&[1, 2, 3, 1]));
println!("{}", describe(&[]));
}The pieces of the pattern are:
[]matches only an empty slice.[_]matches exactly one element...matches any number of elements, including zero. A pattern can contain at most one...firstandlastbind references (&i32), because you matched on a borrowed slice.- The guard
if first == lastruns only after the shape matches.
Arms are tried from top to bottom. A one-element slice reaches [_] before it can reach [_, ..]. The last arm is needed for exhaustiveness: [] and [_, ..] together cover every length.
Binding the rest with @
Write name @ .. to give the skipped part a name. On a slice, the name is a sub-slice. That makes recursion over a slice easy to write:
fn sum(values: &[i32]) -> i32 {
match values {
[] => 0,
[head, tail @ ..] => head + sum(tail),
}
}
fn main() {
println!("{}", sum(&[1, 2, 3, 4]));
}Here tail has type &[i32], so you can pass it straight back to sum.
Matching arrays
An array pattern works the same way. Its length is part of the type, so a pattern with the wrong number of elements is a compile error. A pattern with .. can still match an array of any size.
fn main() {
let arr = [10, 20, 30, 40];
let [a, b, ..] = arr;
println!("{a} {b}");
let [first, rest @ ..] = arr;
println!("{first} {:?}", rest);
}The let statements compile because they cannot fail for a four-element array. On an array, rest has type [i32; 3], which is a copy of the remaining elements and not a borrow.
A slice pattern in let can fail, because the slice might be too short. Use if let or let ... else there:
fn main() {
let data = vec![5, 6];
let [x, y, z] = data[..] else {
println!("need exactly three elements");
return;
};
println!("{x} {y} {z}");
}Common errors
- Non-exhaustive patterns. Matching a slice with
[]and[_]only is rejected, because longer slices are uncovered. Add[_, ..]or_. - Two
..in one pattern.[.., x, ..]is ambiguous and does not compile. - Wrong array length.
let [a, b] = [1, 2, 3];fails to compile. Add..or fix the count. - Matching a
Vecdirectly. AVec<i32>is not a slice. Match onv.as_slice()or&v[..].
Exercise
Write a function ends(values: &[i32]) -> Option<(i32, i32)> that returns the first and last elements. It should return None for an empty slice, and a one-element slice should give that element twice. Which patterns do you need?
Show answer
Use match values { [] => None, [only] => Some((*only, *only)), [first, .., last] => Some((*first, *last)) }. The three arms cover empty, one element, and two or more. The bindings are &i32, so dereference them with * to build the tuple.