Rust Recipes is a problem-oriented series of articles that assist developers while learning Rust. Every article solves simple, everyday development tasks using the Rust standard library or leveraging popular and proven crates.

Question: How to use pattern matching in Rust?

In Rust, pattern matching is a powerful language feature that allows you to destructure data and match it against specific patterns. It helps you handle different cases and extract values from complex data structures with concise and readable code. The match keyword is used to perform pattern matching. Inside a match block, you define patterns and corresponding code blocks for each pattern. When the input data matches a specific pattern, the corresponding code block will be executed.

For demonstration purposes, let’s consider having the following enum to deal with weather conditions:

RUST
enum Weather {
    Sunny,
    Cloudy,
    // the u32 represents the amount of rainfall in millimeters
    Rainy(u32),
    Snowy { snow_depth: u32 },
}

With the Weather enum in place, we can use pattern matching to control the flow of our application:

RUST
fn main() {
    let today_weather = Weather::Rainy(25);
    match today_weather {
        Weather::Sunny => println!("It's a sunny day!"),
        Weather::Cloudy => println!("It's a cloudy day."),
        Weather::Rainy(amount) => println!("It's a rainy day. Rainfall: {amount}mm"),
        Weather::Snowy { snow_depth } => {
            println!("It's a snowy day.");
            println!("Snow Depth: {snow_depth}cm");
        }
    }
}

We can optimize the previous code and assign the actual message to a local variable. To do so, every “arm” must return a value of the same type (String here):

RUST
fn main() {
    let today_weather = Weather::Rainy(25);

    let message = match today_weather {
        Weather::Sunny => String::from("It's a sunny day!"),
        Weather::Cloudy => String::from("It's a cloudy day."),
        Weather::Rainy(amount) => format!("It's a rainy day. Rainfall: {amount}mm"),
        Weather::Snowy {snow_depth} => format!("It's a snowy day.\nSnow Depth: {snow_depth}cm"),
    };
    println!("{message}");
}

Pattern matching also comes with a wildcard pattern. The wildcard pattern (_) in Rust’s pattern matching acts as a default case, handling unmatched situations. It allows us to ignore specific values or variants, ensuring exhaustiveness and providing concise, robust code. Again, let’s take the Weather enum from the previous sample and implement pattern matching using the wildcard pattern:

RUST
fn main() {
    let today_weather = Weather::Rainy(25);

    let message = match today_weather {
        Weather::Sunny => String::from("It's a sunny day!"),
        Weather::Cloudy => String::from("It's a cloudy day."),
        _ => String::from("Weather is not that good today.")
    };
    println!("{message}");
}

Besides these basics, pattern matching has a few more tricks up its sleeve. The following samples show some of the patterns I use most often.

Match guards

A match guard is an additional if condition attached to a pattern. The arm is only taken if the pattern matches and the guard evaluates to true:

RUST
fn describe(weather: Weather) -> String {
    match weather {
        Weather::Rainy(mm) if mm > 50 => format!("Heavy rain: {mm}mm. Stay inside!"),
        Weather::Rainy(mm) => format!("Light rain: {mm}mm."),
        Weather::Snowy { snow_depth } if snow_depth >= 30 => "Deep snow, grab a shovel.".to_string(),
        Weather::Snowy { .. } => "A bit of snow.".to_string(),
        _ => "Nothing special.".to_string(),
    }
}

Notice the { .. } in the second Snowy arm. It tells Rust that we do not care about any of the fields. Arms are evaluated top to bottom, so more specific arms must come before more generic ones.

Ranges and @ bindings

Numbers and characters can be matched against ranges (start..=end). If you need the actual value in the arm, bind it to a name using the @ operator:

RUST
fn describe_temperature(temp: i32) -> String {
    match temp {
        i32::MIN..=-1 => "Freezing".to_string(),
        0 => "Exactly zero".to_string(),
        t @ 1..=15 => format!("Chilly ({t}°C)"),
        t @ 16..=25 => format!("Pleasant ({t}°C)"),
        t => format!("Hot ({t}°C)"),
    }
}

The last arm, t, is a catch-all that binds the value to a variable. Use it instead of _ if you want to work with the remaining values.

Multiple patterns

Use the | operator to combine patterns in a single arm. Ranges work for char too:

RUST
fn classify(c: char) -> &'static str {
    match c.to_ascii_lowercase() {
        'a' | 'e' | 'i' | 'o' | 'u' => "vowel",
        'a'..='z' => "consonant",
        '0'..='9' => "digit",
        _ => "something else",
    }
}

Tuples and nested patterns

Patterns can be nested to destructure complex data in one go. Here is a match over a tuple, followed by one that digs into an Option holding an enum:

RUST
fn locate(point: (i32, i32)) -> &'static str {
    match point {
        (0, 0) => "origin",
        (x, 0) | (0, x) if x > 0 => "positive axis",
        (_, 0) | (0, _) => "negative axis",
        _ => "somewhere else",
    }
}

enum Command {
    Move { x: i32, y: i32 },
    Write(String),
    Quit,
}

fn run(cmd: Option<Command>) -> String {
    match cmd {
        Some(Command::Move { x: 0, y }) => format!("moving vertically by {y}"),
        Some(Command::Move { x, y: 0 }) => format!("moving horizontally by {x}"),
        Some(Command::Move { x, y }) => format!("moving by {x}/{y}"),
        Some(Command::Write(text)) if text.is_empty() => "nothing to write".to_string(),
        Some(Command::Write(text)) => format!("writing '{text}'"),
        Some(Command::Quit) => "bye".to_string(),
        None => "no command".to_string(),
    }
}

In the Move arms, x: 0 is a literal pattern for one field while y binds the other field to a variable.

Slice patterns

Slices and arrays can be matched too. The .. pattern matches any number of elements, and rest @ .. binds them to a variable:

RUST
fn describe_slice(values: &[i32]) -> String {
    match values {
        [] => "empty".to_string(),
        [only] => format!("one element: {only}"),
        [first, .., last] if first == last => format!("starts and ends with {first}"),
        [first, rest @ ..] => format!("starts with {first}, followed by {} more", rest.len()),
    }
}

if let, let else, and matches!

A full match is overkill if you only care about a single pattern. In such cases, if let is more concise:

RUST
let maybe_port = Some(8080u16);

if let Some(port @ 1024..=65535) = maybe_port {
    println!("Unprivileged port {port}");
}

let else is great for early returns. It binds the variable if the pattern matches and diverges (return, break, continue, or panic!) otherwise:

RUST
fn parse_port(input: &str) -> Result<u16, String> {
    let Ok(port) = input.parse::<u16>() else {
        return Err(format!("'{input}' is not a valid port"));
    };
    Ok(port)
}

Finally, the matches! macro evaluates to a bool and is perfect for quick checks, optionally including a guard:

RUST
let is_rainy = matches!(Weather::Rainy(5), Weather::Rainy(_));
let is_heavy = matches!(Weather::Rainy(80), Weather::Rainy(mm) if mm > 50);

Pattern matching is easy to grasp and use, yet it is a powerful language feature that you can use to streamline your code, make it more readable, and increase maintainability. Because the compiler enforces exhaustiveness, adding a new variant to an enum immediately shows you every match that needs attention.

Want more Rust fundamentals? Check out Shadowing and Temporary Mutability in Rust and learn how to implement the builder pattern .