Lesson 14 of 20

Pattern Matching

Pattern Matching

match is one of Rust's most powerful features. It compares a value against a series of patterns and executes the first that matches.

Range Patterns

match n {
    1..=5 => "one to five",
    6..=10 => "six to ten",
    _ => "other",
}

Guard Clauses

Add if conditions to match arms:

match pair {
    (x, y) if x == y => "equal",
    (x, y) if x > y => "first larger",
    _ => "second larger",
}

Destructuring

Match can destructure tuples, structs, enums, and slices:

// Destructure a tuple
let (a, b) = (1, 2);

// Destructure in match
match point {
    Point { x: 0, y } => println!("On y-axis at {}", y),
    Point { x, y: 0 } => println!("On x-axis at {}", x),
    Point { x, y } => println!("At ({}, {})", x, y),
}

// Slice patterns
match slice {
    [] => "empty",
    [x] => "one element",
    [first, .., last] => "many elements",
}

if let

For matching a single pattern, if let is more concise:

if let Some(n) = maybe_number {
    println!("Got {}", n);
}

while let

while let Some(top) = stack.pop() {
    println!("{}", top);
}

Your Task

  1. classify(n: i32) -> &'static str — "negative", "zero", "small" (1-100), or "large".
  2. describe_pair(pair: (i32, i32)) -> String — "origin", "x:N", "y:N", "diag:N", or "(x,y)".
  3. head_tail(v: &[i32]) -> String — "empty", "single:N", or "head:N tail:N".
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.