Rest Patterns Ignore Middle Elements

Ignore middle elements with rest patterns: .. binds prefixes, suffixes, or both ends, and match dispatches unknown-length slices by shape.

RustCli Tooling

Code

rustsnippet
27 lines
fn main() {
    let scores = [91, 78, 85, 62, 99];

    // .. swallows any number of middle elements: prefixes and suffixes both bind
    let [top, second, ..] = scores;
    println!("top: {top}, second: {second}");

    let [.., second_last, last] = scores;
    println!("second last: {second_last}, last: {last}");

    let [first, .., final_score] = scores;
    println!("first: {first}, final: {final_score}");

    // A tuple's middle span is absorbed by .. the same way
    let point = (3, 7, 11, 15);
    let (x, .., w) = point;
    println!("x: {x}, w: {w}");

    // Slices of unknown length: rest patterns let match dispatch by shape
    for data in [vec![5], vec![1, 2, 3], vec![]] {
        match data.as_slice() {
            [only] => println!("single: {only}"),
            [first, .., last] => println!("from {first} to {last}"),
            [] => println!("empty"),
        }
    }
}

How it works

The snippet is organized around the function main.

Repetition is confined to for data in [vec![5], vec![1, 2, 3], vec![]] — the rest of the file is straight-line. Pattern matching via match forces each shape of the value to be handled.

What to watch for

  • No external surface: all behavior comes from the standard library.

Applying it

Entry signature: fn main()

The demo output is labeled (top:, second last:, first:), so every printed line maps back to its originating operation.

Statements that matter

match data.as_slice() {
[only] => println!("single: {only}"),
[first, .., last] => println!("from {first} to {last}"),
[] => println!("empty"),
}

Interactive Tools for This Topic

FAQ

What does Rest Patterns Ignore Middle Elements print when run?
Running the file directly is enough — expect labeled output lines such as `top:`, `second last:`, `first:`.