Sub topic 10
Matching on Slice Patterns
Slice patterns let match, if let, let ... else, and function parameters take a slice apart by its length and by the elements at its ends. This chapter assumes you know the slice type &[T], range slicing, and the borrowing rules for slices from the earlier chapters. It also assumes you are comfortable with match, if let, and Option.
What a slice pattern looks like
A slice pattern is written with square brackets, like an array literal. Each position in the brackets is itself a pattern. The pattern matches only if the slice has the right length and every element pattern matches.
fn describe(s: &[i32]) -> &'static str {
match s {
[] => "empty",
[_] => "one element",
[first, .., last] if first == last => "same first and last",
[_, ..] => "several elements",
}
}
fn main() {
println!("{}", describe(&[]));
println!("{}", describe(&[7]));
println!("{}", describe(&[1, 2, 1]));
println!("{}", describe(&[1, 2, 3]));
}This prints empty, one element, same first and last, and several elements.
Arms are tried from top to bottom, as in any match. The pattern [first, .., last] needs at least two elements, because first and last are different positions. A one-element slice never reaches it.
Fixed-length patterns and the rest pattern
A pattern with no .. matches one exact length. [a, b] matches only slices of length 2. The .. pattern stands for "any number of elements here, including zero". It lets one pattern cover a range of lengths.
| Pattern | Matches slices with | Notes |
|---|---|---|
| `[]` | exactly 0 elements | the empty slice |
| `[x]` | exactly 1 element | |
| `[x, y]` | exactly 2 elements | |
| `[x, ..]` | 1 or more | binds the first element |
| `[.., y]` | 1 or more | binds the last element |
| `[x, .., y]` | 2 or more | binds both ends |
| `[x, rest @ ..]` | 1 or more | `rest` is the remaining subslice |
A pattern may contain at most one ... Writing [.., x, ..] is a compile error, because the compiler could not tell how many elements each .. should absorb. Only the elements next to the edges can be named. To find an element in the middle you need a loop or a method such as iter().position.
The diagram shows how a match on a slice effectively works. The length check comes first, and element checks follow.
Binding the rest with `name @ ..`
To keep the elements that .. skips, bind them with name @ ... The binding is itself a slice. This gives you the classic "head and tail" decomposition.
fn sum(s: &[i32]) -> i32 {
match s {
[] => 0,
[head, tail @ ..] => head + sum(tail),
}
}
fn main() {
println!("{}", sum(&[1, 2, 3, 4]));
}This prints 10. Here head is an &i32 and tail is an &[i32]. The reason is default binding modes. You matched through a reference (s is &[i32]), so every binding in the pattern becomes a reference too. head + sum(tail) compiles because &i32 + i32 is implemented for i32.
Recursion like this reads well, but Rust does not guarantee tail-call optimization. A slice of a million elements can overflow the stack. For real summing, use s.iter().sum(). Use the head and tail form when the recursive structure is the point, such as a small parser.
Exhaustiveness
The compiler checks that slice patterns cover every possible length. If you delete the last arm of describe, you get error E0004. It reports that a pattern like &[_, _, ..] is not covered, so you can see which lengths you missed.
Guards do not count toward coverage. In describe, the arm [first, .., last] if first == last can fail at run time. Without the final [_, ..] arm, a slice like [1, 2, 3] would be unhandled and the code would not compile. When a compile error mentions a missing length, add an arm that ends in .. or _.
Literals and constants inside slice patterns
Element patterns can be literals, ranges, constants, or nested patterns. This suits byte-level work such as checking a file signature.
fn is_png(bytes: &[u8]) -> bool {
matches!(bytes, [0x89, b'P', b'N', b'G', ..])
}
fn main() {
println!("{}", is_png(&[0x89, b'P', b'N', b'G', 13, 10]));
println!("{}", is_png(b"GIF89a"));
}This prints true and then false. The input might be only two bytes long. The pattern needs five, so the match fails safely and cannot read past the end. No panic is possible here, unlike with indexing.
String literals work too, as long as the elements are &str. That makes slice patterns a compact way to dispatch on command-line arguments.
fn run(args: &[&str]) -> String {
match args {
[] => "no command".to_string(),
["help"] => "usage: add|echo".to_string(),
["add", a, b] => match (a.parse::<i32>(), b.parse::<i32>()) {
(Ok(x), Ok(y)) => (x + y).to_string(),
_ => "numbers expected".to_string(),
},
["echo", words @ ..] => words.join(" "),
[other, ..] => format!("unknown command: {other}"),
}
}
fn main() {
println!("{}", run(&[]));
println!("{}", run(&["add", "2", "3"]));
println!("{}", run(&["echo", "a", "b"]));
println!("{}", run(&["rm", "x"]));
}The output is no command, 5, a b, and unknown command: rm. Two details matter here. The arm order puts specific patterns before the catch-all [other, ..]. The bindings a and b have type &&str, but method calls like parse auto-dereference, so you rarely notice.
Mutable slice patterns
Matching on a &mut [T] gives you &mut bindings. Several of them can be live at once, because the pattern proves they refer to different positions.
fn swap_ends(s: &mut [i32]) {
if let [first, .., last] = s {
std::mem::swap(first, last);
}
}
fn main() {
let mut v = [1, 2, 3, 4];
swap_ends(&mut v);
println!("{:?}", v);
let mut short = [9];
swap_ends(&mut short);
println!("{:?}", short);
}This prints [4, 2, 3, 1] and then [9]. Writing the same thing with indexing, std::mem::swap(&mut s[0], &mut s[n - 1]), is rejected by the borrow checker because it takes two &mut borrows of s. The pattern version works because the compiler knows first and last are different elements. For splits at a computed index, you still need split_at_mut, as covered in the mutable slices chapter. Patterns only handle fixed positions at the ends.
A mutable rest binding also works. In [head, rest @ ..], rest is a &mut [i32] that you can pass to another function while head stays usable.
Arrays versus slices
Patterns work on arrays as well as slices, and the difference is worth knowing. An array's length is part of its type, so the compiler can often prove the pattern always matches. In that case you can use it in a plain let.
fn main() {
let [a, b, c] = [1, 2, 3];
let [head, tail @ ..] = [10, 20, 30, 40];
println!("{a} {b} {c}");
println!("{head} {:?}", tail);
}This prints 1 2 3 and then 10 [20, 30, 40]. When you match an array by value, rest @ .. binds an array, here [i32; 3], not a slice. Its length is computed from the array's length.
A slice has no length in its type, so the same pattern can fail. let [a, b] = some_slice; is refutable, which means it might not match. The compiler rejects it. Use if let, match, or let ... else.
fn parse_pair(args: &[&str]) -> Option<(i32, i32)> {
let [a, b] = args else {
return None;
};
Some((a.parse().ok()?, b.parse().ok()?))
}
fn main() {
println!("{:?}", parse_pair(&["3", "4"]));
println!("{:?}", parse_pair(&["3"]));
}This prints Some((3, 4)) and then None. The let ... else form keeps the success path unindented. The else block must diverge, for example with return, break, or panic!.
Gotchas
Vecdoes not match directly. A slice pattern has slice type, somatch &vwithv: Vec<i32>gives a type mismatch. Callv.as_slice()or&v[..]first, as inmatch v.as_slice() { ... }.Stringandstrhave no slice patterns. Patterns apply to[T]only. For text, match ons.as_bytes()when you are working with ASCII bytes. Otherwise collect characters into aVec<char>and match on its slice.Vec<String>cannot match&strliterals. The element type isString, and a literal pattern has type&str. Convert first withargs.iter().map(String::as_str).collect::<Vec<_>>()and match on the resultingVec<&str>.- Moving out of a slice is not allowed. Matching a
&[String]gives you&Stringbindings. To take ownership, match an owned array by value, or clone the element. - Only the ends are addressable. There is one
..per pattern, so you cannot name elements on both sides of a middle section.
fn main() {
let v = vec![3, 1, 4];
match v.as_slice() {
[first, .., last] => println!("{first} {last}"),
_ => println!("too short"),
}
}This prints 3 4. It shows the as_slice step that the first gotcha requires.
When to use patterns and when not to
Slice patterns work best when the shape of the data decides the logic, as in commands, small recursive functions, and byte headers. Prefer them over index arithmetic in these cases, because the length check and the element access happen together and cannot disagree. Prefer iterators and methods like split_first, windows, and chunks when you process many elements or an unknown count. split_first returns Option<(&T, &[T])>. It does the same work as [head, tail @ ..] and is easier to chain with other Option methods.
There is no allocation or hidden cost. A pattern compiles to a length comparison and direct element reads, the same checks you would write by hand.
Exercise
Write a function fn middle_sum(s: &[i32]) -> Option<i32> that returns the sum of every element except the first and the last. It returns None when the slice has fewer than two elements. Use a slice pattern.
Show answer
Use [_, middle @ .., _]. The function is match s { [_, middle @ .., _] => Some(middle.iter().sum()), _ => None }. The pattern needs at least two elements, so shorter slices fall into the _ arm. For exactly two elements, middle is the empty slice and the sum is 0.
Exercise
Why does let [a, b] = slice; fail to compile when slice has type &[i32], and what are two ways to fix it?
Show answer
The pattern is refutable. A slice can have any length at run time, so [a, b] may not match, and a plain let requires a pattern that always matches. Fix it with if let [a, b] = slice { ... } (or a match with a fallback arm), or with let [a, b] = slice else { return; };. If the value is an array [i32; 2], the plain let compiles because the length is known.
Exercise
Given args: Vec<String>, how do you match it against ["add", a, b], and why can't you write match args.as_slice() with that pattern directly?
Show answer
as_slice() gives &[String]. A string literal pattern has type &str, so it cannot match a String element. Convert first with let args: Vec<&str> = args.iter().map(String::as_str).collect(); and then use match args.as_slice() { ["add", a, b] => ..., _ => ... }.