Rust Lesson 20 – Pattern Matching | Dataplexa

Pattern Matching in Rust

In this lesson, you will learn about pattern matching in Rust. Pattern matching allows you to compare values against patterns and execute code based on which pattern matches.

It is one of Rust’s most powerful features and is commonly used with enums, options, results, and complex data structures.


What Is Pattern Matching?

Pattern matching is a way to check a value against multiple patterns and run different code for each match.

Rust uses the match keyword for pattern matching.


Basic match Expression

A match expression compares a value against multiple arms. Each arm consists of a pattern and the code to execute.

let number = 3;

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

The underscore _ acts as a default case.


Matching with Enums

Pattern matching is most commonly used with enums.

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

let dir = Direction::East;

match dir {
    Direction::North => println!("Go north"),
    Direction::South => println!("Go south"),
    Direction::East => println!("Go east"),
    Direction::West => println!("Go west"),
}

Destructuring Enum Data

You can extract values stored inside enum variants.

enum Message {
    Move(i32, i32),
    Write(String),
    Quit,
}

let msg = Message::Move(10, 20);

match msg {
    Message::Move(x, y) => println!("Move to {}, {}", x, y),
    Message::Write(text) => println!("{}", text),
    Message::Quit => println!("Quit"),
}

Matching Option Values

The Option enum is often handled using pattern matching.

let value = Some(5);

match value {
    Some(v) => println!("Value: {}", v),
    None => println!("No value"),
}

Matching Result Values

The Result enum is used for error handling and is also matched using match.

let result: Result = Ok(10);

match result {
    Ok(v) => println!("Success: {}", v),
    Err(e) => println!("Error: {}", e),
}

Match Must Be Exhaustive

Rust requires match expressions to be exhaustive. All possible cases must be handled.

Using _ ensures that unmatched cases are covered.


Using match as an Expression

match can return values. Each arm must return the same type.

let num = 4;

let result = match num {
    1 => "One",
    2 => "Two",
    3 => "Three",
    _ => "Other",
};

println!("{}", result);

if let Syntax

For simple matching, Rust provides if let as a concise alternative.

let value = Some(8);

if let Some(v) = value {
    println!("Value is {}", v);
}

Why Pattern Matching Matters

Pattern matching helps Rust programs:

  • Handle complex logic clearly
  • Avoid runtime errors
  • Work safely with enums
  • Write expressive, readable code

📝 Practice Exercises


Exercise 1

Create a match statement that handles numbers 1 to 5.

Exercise 2

Match on an enum with associated data.

Exercise 3

Use match with Option.

Exercise 4

Rewrite a match using if let.


✅ Practice Answers


Answer 1

let n = 3;

match n {
    1 => println!("One"),
    2 => println!("Two"),
    3 => println!("Three"),
    4 => println!("Four"),
    5 => println!("Five"),
    _ => println!("Other"),
}

Answer 2

enum Shape {
    Circle(f64),
    Square(f64),
}

let s = Shape::Circle(2.5);

match s {
    Shape::Circle(r) => println!("Radius {}", r),
    Shape::Square(a) => println!("Side {}", a),
}

Answer 3

let opt = Some(10);

match opt {
    Some(v) => println!("{}", v),
    None => println!("None"),
}

Answer 4

if let Some(v) = opt {
    println!("{}", v);
}

What’s Next?

Now that you understand pattern matching, the next lesson will cover memory management and how Rust handles memory safely without a garbage collector.