0Pricing
Learn Rust Coding · Lesson

Powerful Pattern Matching

Master `match` expressions and other pattern matching constructs for concise and exhaustive handling of data variants.

Unleashing Pattern Matching

Welcome to the world of pattern matching in Rust! This powerful feature allows you to control program flow based on the structure of data.

Instead of just checking equality, you can deconstruct values, extract components, and execute specific code for different data shapes.

  • It's like a super-powered if/else or switch statement.
  • Ensures exhaustiveness: you must handle all possible patterns.
  • Makes code more readable and robust.

The `match` Expression Basics

The core of pattern matching is the match expression. It takes a value and compares it against a series of patterns. The first pattern that matches wins!

Each 'arm' of a match expression consists of a pattern and the code to execute if that pattern matches.

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

fn main() {
  let my_direction = Direction::North;

  match my_direction {
    Direction::North => println!("Going up!"),
    Direction::East => println!("Going right!"),
    Direction::South => println!("Going down!"),
    Direction::West => println!("Going left!"),
  }
}

All lessons in this course

  1. Defining and Using Structs
  2. Enums for Custom Types
  3. Powerful Pattern Matching
← Back to Learn Rust Coding