Rust Control Flow
Estimated reading: 3 minutes 427 views

🦀 Rust – Match (Switch Equivalent): Pattern Matching with Power and Precision

Introduction – Why Learn match in Rust?

Rust doesn’t have a traditional switch statement like C or JavaScript. Instead, it provides match—a powerful, exhaustive, and expressive pattern matching construct. It’s not just a switch; it’s an essential feature for control flow, enum handling, and data destructuring.

In this guide, you’ll learn:

  • How match works as a switch alternative
  • Pattern matching with values, ranges, and enums
  • Match expressions with return values
  • Real output and line-by-line explanations

Basic match Syntax

Code Example:

fn main() {
    let grade = 'A';

    match grade {
        'A' => println!("Excellent"),
        'B' => println!("Good"),
        'C' => println!("Average"),
        _   => println!("Needs Improvement"),
    }
}

Explanation:

  • match grade checks the value of grade
  • Each 'X' => arm matches a character and runs the corresponding block
  • _ is the wildcard pattern (default case)

Output:

Excellent

Match as an Expression (Value Returning)

Code Example:

fn main() {
    let code = 200;

    let status = match code {
        200 => "OK",
        404 => "Not Found",
        500 => "Server Error",
        _   => "Unknown",
    };

    println!("Status: {}", status);
}

Explanation:

  • match returns a value (&str here)
  • The status variable is assigned based on the pattern
  • All branches must return the same type

Output:

Status: OK

Match with Ranges

Code Example:

fn main() {
    let score = 78;

    let grade = match score {
        90..=100 => "A",
        80..=89  => "B",
        70..=79  => "C",
        60..=69  => "D",
        _        => "F",
    };

    println!("Grade: {}", grade);
}

Explanation:

  • Rust supports 90..=100 to match inclusive ranges
  • Each range is checked top-down
  • score = 78 matches 70..=79, returning "C"

Output:

Grade: C

Match with Multiple Patterns

Code Example:

fn main() {
    let day = 7;

    match day {
        1 | 7 => println!("Weekend"),
        2..=6 => println!("Weekday"),
        _     => println!("Invalid"),
    }
}

Explanation:

  • 1 | 7 means either 1 or 7
  • 2..=6 matches any weekday number
  • _ handles invalid cases

Output:

Weekend

Match with Enums

enum Direction {
    North,
    South,
    East,
    West,
}

fn main() {
    let dir = Direction::East;

    match dir {
        Direction::North => println!("Up"),
        Direction::South => println!("Down"),
        Direction::East  => println!("Right"),
        Direction::West  => println!("Left"),
    }
}

Explanation:

  • Direction is a custom enum
  • match exhaustively checks each variant
  • All variants are explicitly handled

Output:

Right

Common match Mistakes

MistakeError/ProblemSolution
Missing wildcard or full matchNon-exhaustive patternsAdd _ => or handle all possibilities
Mismatched return typesType mismatch in branchesEnsure all arms return same type
Forgetting to bind valuesPattern doesn’t extract valuesUse Some(x) or Ok(val) with binding

Summary – Recap & Next Steps

Rust’s match goes far beyond a basic switch. It supports pattern matching, expressions, ranges, enums, and destructuring, making it one of the most versatile tools in the language.

Key Takeaways:

  • match is exhaustive and safe
  • Can return values like if expressions
  • Use ranges, multiple patterns, and wildcards effectively
  • Essential for working with enums and control flow

Up next: Learn about Rust – Decision Making, where you’ll combine if, match, and logical expressions.


FAQs


Is match the same as switch in C/C++?
Not exactly. match is more powerful—supports ranges, multiple patterns, and destructuring.


Does Rust require all match arms to be handled?
Yes. Rust enforces exhaustiveness. You must handle all possible cases or use _ as a catch-all.


Can I return values from a match?
Absolutely. match is an expression—just like if. All arms must return the same type.


Can I use match with enums and custom types?
Yes! match is perfect for enums. It’s also used for handling Option, Result, and custom patterns.


Share Now :
Share

Rust – Match (Switch Equivalent)

Or Copy Link

CONTENTS
Scroll to Top