Menu
Coddy logo textTech

The 'match' Expression

Part of the Logic & Flow section of Coddy's Rust journey — lesson 1 of 66.

The match expression is Rust's powerful pattern matching tool that lets you compare a value against different patterns and execute code based on which pattern matches. Think of it as a more advanced version of if statements that can handle multiple conditions elegantly.

Here's the basic syntax of a match expression:

match value {
    pattern1 => code_to_run,
    pattern2 => code_to_run,
    _ => default_code,
}

Each line inside the match is called an "arm." The => separates the pattern from the code that runs when that pattern matches. The underscore _ is a special wildcard pattern that matches anything - it's like a "catch-all" for any value that doesn't match the other patterns.

Here's a simple example that checks a number:

let number = 2;

match number {
    1 => println!("One"),
    2 => println!("Two"),
    _ => println!("Other"),
}

In Rust, match expressions must be exhaustive, meaning they must handle every possible value. That's why the wildcard _ is so important - it ensures you've covered all cases that weren't explicitly matched.

challenge icon

Challenge

Easy
Write a function describe_number that takes num and returns a string description based on the number's value.

Use a match expression to return different descriptions for different numbers.

Conditions:

  • If num is 0, return "zero"
  • If num is 1, return "one"
  • If num is 2, return "two"
  • If num is 3, return "three"
  • For any other number, return "many"

Parameters:

  • num (i32): The number to describe

Returns: A string description of the number (String)

Cheat sheet

The match expression compares a value against different patterns and executes code based on which pattern matches:

match value {
    pattern1 => code_to_run,
    pattern2 => code_to_run,
    _ => default_code,
}

Each line inside the match is called an "arm." The => separates the pattern from the code that runs when that pattern matches.

Example:

let number = 2;

match number {
    1 => println!("One"),
    2 => println!("Two"),
    _ => println!("Other"),
}

The underscore _ is a wildcard pattern that matches anything not covered by other patterns. match expressions must be exhaustive - they must handle every possible value.

Try it yourself

fn describe_number(num: i32) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow