typestar

match expressions in Rust

Exhaustive pattern matching over a value.

fn describe(n: i32) -> String {
    match n {
        0 => "zero".to_string(),
        1 | 2 | 3 => "small".to_string(),
        4..=9 => "medium".to_string(),
        _ if n < 0 => "negative".to_string(),
        _ => "large".to_string(),
    }
}

fn main() {
    println!("{}", describe(7));
}

How it works

  1. Literal, or-pattern, and range arms match values.
  2. A guard if n < 0 refines an arm.
  3. _ is the catch-all; match must be exhaustive.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
243
Tokens
98
Three-star pace
90 tpm

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

Type this snippet

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

← Previous Next →