Sub topic 10
Matching on Slice Patterns
This chapter assumes you know match and if let on enums, and that you can borrow a slice (&[T]) from an array or Vec. Slice patterns let you test a slice's length and bind its elements in one expression. They work well when the shape of the data decides what the code does.
Basic shapes
A slice pattern is written with square brackets. Each position in the pattern matches one element. The .. pattern matches any number of elements, including zero. A pattern may contain .. at most once.
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]));
}The program prints empty, one element, same first and last, and several elements. Arms are tried from top to bottom. The pattern [first, .., last] needs at least two elements. The if after it is a match guard, an extra condition that must also be true. The last arm catches every non-empty slice that the earlier arms did not take.
Binding the rest of a slice
To keep the elements that .. skips, give it a name with @. The name rest @ .. binds a sub-slice. Because the match is on a &[T], the binding is itself a &[T], so no data is copied.
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 a &i32 and tail is a &[i32] that views the remaining elements. Recursion over head and tail is a common use of this form. For long slices, an iterator such as iter().sum() is better, because it does not grow the stack.
Matching literals
Elements can be literal values, so a pattern can check the contents as well as the length. This is useful for small command parsers.
fn run(args: &[&str]) -> String {
match args {
[] => "no command".to_string(),
["help"] => "usage: add A B | greet NAME...".to_string(),
["add", a, b] => format!("adding {a} and {b}"),
["greet", names @ ..] => format!("hello {}", names.join(" ")),
[other, ..] => format!("unknown command: {other}"),
}
}
fn main() {
println!("{}", run(&[]));
println!("{}", run(&["add", "2", "3"]));
println!("{}", run(&["greet", "Ada", "Grace"]));
println!("{}", run(&["add", "2"]));
}The last call has add with only one argument. It fails the ["add", a, b] arm because the length is wrong. It reaches the final arm and prints unknown command: add.
Mutable matches
When you match on a &mut [T], the bindings become mutable references. You can change elements through them.
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);
}This prints [4, 2, 3, 1]. If the slice has fewer than two elements, the if let does not match and nothing happens. Unlike s[0], the pattern cannot panic from an out-of-range index.
Where patterns apply
Slice patterns apply to slices, arrays, and references to them. A Vec<T> is not a slice, so convert it first with as_slice() or &v[..].
fn main() {
let v = vec![10, 20, 30];
match v.as_slice() {
[a, b, c] => println!("three: {a} {b} {c}"),
_ => println!("other length"),
}
let arr = [1, 2, 3];
let [x, y, z] = arr;
println!("{}", x + y + z);
}The array pattern [x, y, z] works with let with no match, because an array's length is part of its type. The compiler knows the pattern always matches. A pattern on a slice is not irrefutable in the same way, so a plain let fails to compile. Use match or if let for slices.
Exercise
A function matches on s: &[i32] with the arms [a, b, rest @ ..] and []. Which input lengths does the match fail to cover, and what is the type of rest?
Show answer
It fails to cover length 1, so the compiler rejects the match as non-exhaustive. Adding an arm [_] or a wildcard _ fixes it. The type of rest is &[i32], a sub-slice that starts at the third element.
Exercise
Write a function ends(s: &[i32]) -> Option<(i32, i32)> that returns the first and last elements. For a one-element slice, both values are that element. For an empty slice, return None.
Show answer
fn ends(s: &[i32]) -> Option<(i32, i32)> { match s { [] => None, [x] => Some((x, x)), [first, .., last] => Some((first, last)) } }