typestar

Slice patterns in Rust

Matching on the shape of a slice: empty, one element, first and last, the middle.

fn summarize(values: &[i32]) -> String {
    match values {
        [] => "empty".to_string(),
        [only] => format!("just {only}"),
        [first, .., last] => format!("{first} to {last}"),
    }
}

fn main() {
    println!("{}", summarize(&[]));
    println!("{}", summarize(&[5]));
    println!("{}", summarize(&[1, 2, 3]));

    if let [head, tail @ ..] = &[10, 20, 30][..] {
        println!("{head} then {:?}", tail);
    }
}

How it works

  1. [] matches an empty slice, [only] exactly one element.
  2. [first, .., last] needs at least two elements.
  3. rest @ .. binds the remainder as a slice.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
376
Tokens
144
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 96 seconds.

Type this snippet

Step 4 of 4 in Pattern matching, step 22 of 39 in Language basics.

← Previous Next →