skip to content

In Rust, how do slice patterns like `[first, .., last]` and `[cmd, args @ ..]` match a `&[T]`, and when is such a match exhaustive?

level: middleimportance: should knowfreq 35%

answer

  1. every pattern implies a length
  2. the rest pattern matches zero or more
  3. binding a subslice with @
  4. the empty slice is a case too

basics

~20 s

Each slice pattern fixes a length: [] is zero, [x] exactly one, [first, .., last] two or more, and [cmd, args @ ..] one or more, binding args to the rest as a subslice. A slice match is exhaustive only when every length, zero included, is covered.

solid answer

~40 s

Slice patterns destructure arrays and slices by position. On a `&[T]` scrutinee the elements bind by reference (`first: &T`), and `..`, the **rest pattern**, matches zero or more elements and may appear once. `name @ ..` binds those elements as a subslice, so `[cmd, args @ ..]` gives `args: &[T]` with no copy. Element patterns can be literals, as in `["DELETE", table]`. Because a slice's length is known only at run time, rustc checks exhaustiveness over lengths: arms `[only]` and `[first, .., last]` miss the empty slice and fail with E0004, "non-exhaustive patterns: `&[]` not covered". A `let` needs an irrefutable pattern, so `let [p] = v[..];` is E0005 unless written as `let ... else`; on a fixed-size array the length is in the type, so `let [x, .., z] = arr;` compiles.

code

rust · 26 lines
rust
fn describe(fields: &[&str]) -> String {
    match fields {
        [] => "empty line".to_string(),
        [only] => format!("one field: {only}"),
        [first, .., last] => format!("{} fields, {first} .. {last}", fields.len()),
    }
}

fn run(fields: &[&str]) {
    match fields {
        ["DELETE", table] => println!("delete everything in {table}"),
        [cmd, args @ ..] => println!("{cmd} with {} args: {args:?}", args.len()),
        [] => println!("nothing to run"),
    }
}

fn main() {
    let line = "INSERT,users,alice,admin";
    let fields: Vec<&str> = line.split(',').collect();
    println!("{}", describe(&fields));
    println!("{}", describe(&fields[..1]));
    println!("{}", describe(&[]));
    run(&fields);
    run(&["DELETE", "sessions"]);
    run(&[]);
}

go deeper

for a junior

Recall the basic forms: [] for empty, [x] for one element, [first, .., last] for both ends, and that .. stands for any number of elements.

for a middle

Explain the length each pattern requires, that name @ .. binds a borrowed subslice, and why omitting the empty case is E0004.

for a senior

Use slice patterns in parsers instead of indexing so a short input falls to an arm rather than panicking, and know the let-else form for slices and why arrays are irrefutable.

for a principal

Prefer patterns over index arithmetic in input-handling code, since the compiler then checks every length case and reviewers no longer have to.

## Slice patterns by length A slice pattern lists element patterns inside square brackets. The Rust Reference says slice patterns "can match both arrays of fixed size and slices of dynamic size". On a slice, each pattern states a length requirement as well as bindings: | Pattern | Matches slices of length | Binds | |---|---|---| | `[]` | exactly 0 | nothing | | `[only]` | exactly 1 | `only` | | `[a, b]` | exactly 2 | `a`, `b` | | `[first, .., last]` | 2 or more | `first`, `last` | | `[head, rest @ ..]` | 1 or more | `head`, and `rest` as a subslice | | `[first, middle @ .., last]` | 2 or more | the ends, and `middle` as a subslice | | `[..]` or `[all @ ..]` | any, including 0 | `all` as the whole slice | The `..` token is the **rest pattern**. It matches zero or more elements not matched before or after it, and it may appear only once in a slice pattern. Written as `name @ ..`, it binds those elements as a slice of their own. A frequent slip: `[first, .., last]` does **not** match a one-element slice. `first` and `last` are two distinct positions, so the pattern needs at least two elements, and a one-element slice needs its own `[only]` arm. ## A CSV command dispatcher ```rust fn run(fields: &[&str]) { match fields { ["DELETE", table] => println!("delete everything in {table}"), [cmd, args @ ..] => println!("{cmd} with {} args: {args:?}", args.len()), [] => println!("nothing to run"), } } ``` - **Literals as element patterns.** `["DELETE", table]` matches exactly two fields whose first one is the string `DELETE`. Arms are tried top to bottom, so it wins over the general arm below it. - **Bindings by reference.** The scrutinee is a `&[&str]`, so default binding modes make `table` and `cmd` bind as `&&str` and `args` as `&[&str]`; no element is moved or copied. (The general binding-mode rules are covered with destructuring.) - **A subslice, not a new collection.** `args` points into the same buffer as `fields`; it is a fat pointer with a shorter length. ## Exhaustiveness over lengths For an enum, exhaustiveness is about variants. For a slice, it is about lengths. Write only `[only]` and `[first, .., last]` arms and rustc 1.99.1 refuses: ```plaintext error[E0004]: non-exhaustive patterns: `&[]` not covered ``` The checker reasons over lengths: `[only]` covers 1, `[first, .., last]` covers 2 and up, so 0 is missing. Adding a `[]` arm, or a final `_` arm, fixes it. ## `let`, `if let` and `let ... else` 1. **`let` needs an irrefutable pattern.** On a slice, only the forms made of a single rest pattern, such as `[..]` or `[all @ ..]`, are irrefutable. `let [p] = v[..];` fails with E0005, "refutable pattern in local binding", and rustc suggests `let ... else`. 2. **Arrays are different.** An array's length is part of its type, so `let [x, .., z] = [1, 2, 3];` is irrefutable and compiles; rustc even warns that an `if let` with such a pattern is pointless. 3. **`let ... else` covers the short case.** `let [head, rest @ ..] = fields else { return };` binds on success and diverges otherwise. 4. **A `Vec` is not a slice.** `match v { [a, b] => ... }` on a `Vec` fails with E0529, "expected an array or slice, found `Vec<{integer}>`" for `let v = vec![1, 2];`; match on `v.as_slice()` or `&v[..]` instead. ## Where slice patterns beat indexing - **No panics.** `fields[0]` panics on an empty slice; a pattern cannot, because a length that does not fit simply falls through to the next arm. - **The compiler tracks the cases.** In a `match` without a catch-all arm, forgetting a length is a compile error from exhaustiveness checking, not a run-time surprise. - **Mutable views.** Matching a `&mut [T]` binds `&mut T`, so `if let [first, .., last] = buf { std::mem::swap(first, last); }` swaps the two ends in place. ## What to say in an interview - State the length each pattern requires, and that `[first, .., last]` needs two elements. - Explain that `name @ ..` binds a borrowed subslice, never a copy. - Show that exhaustiveness on a slice is over lengths, and quote the `&[]` case rustc reports. - Contrast slices, whose length is a run-time value, with arrays, whose length makes many patterns irrefutable.

  • How do you bind the middle of a slice while also naming its two ends?
    Put a binding on the rest pattern: `[first, middle @ .., last]`. `middle` is a `&[T]` of the elements between the ends, possibly empty, and the whole pattern still requires at least two elements. It is a borrowed subslice of the original, so nothing is copied.
  • Can you match a `Vec<T>` against slice patterns directly?
    Not the `Vec` itself: `match v { [a, b] => ... }` on `let v = vec![1, 2];` fails with E0529, "expected an array or slice, found `Vec<{integer}>`". Match on a slice of it instead, `v.as_slice()` or `&v[..]`, and the elements bind by reference; match on `&mut v[..]` to get `&mut T` bindings.

  • [first, .., last] also matches a one-element slice, binding first and last to it.
  • A match on a slice with [x] and [x, ..] arms is exhaustive.
  • The rest pattern copies the remaining elements into a new Vec.
  • Slice patterns only work on fixed-size arrays, not on &[T].
  • let [x] = v[..]; compiles whenever the vector happens to hold one element.