pattern

Rust Match a slice by its shape

Slice patterns can distinguish empty slices from slices with elements, and capture the remaining part without constructing a new vector. Expected output (not executed): 4: 2 Why: The pattern binds the first element and a borrowed view of the other two. Common mistake: A pattern with exactly two elements does not match slices of arbitrary length.

Formal Syntax & Structure

rust syntaxrust
match slice { [first, rest @ ..] => ..., [] => ... }

Working Example

Example Snippetrust
fn main() {    let data = [4, 9, 2];    let view = &data[..];    match view {        [] => println!("empty"),        [first, rest @ ..] => println!("{first}: {}", rest.len()),    }}
Rust Reference