Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Pattern Matching | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 15 of 50

·rust

Pattern Matching

18 minutes

Course progress30%

Pattern Matching

Pattern matching is a powerful feature for destructuring and checking values. It goes beyond just enums—you can match on structs, tuples, arrays, and more.

Basic Match Syntax

match is exhaustive—all possibilities must be handled:

match value {
    pattern1 => result1,
    pattern2 => result2,
    _ => default_result,  // Catch-all
}

Matching Enums with Data

  {
    Quit,
    Move { x: , y:  },
    (),
    (, , ),
}

 (msg: Message) {
     msg {
        Message::Quit => (\
enum
Message
i32
i32
Write
String
ChangeColor
i32
i32
i32
fn
process
match
println!
"Quit\"), Message::Move { x, y } => { println!(\"Move to ({}, {})\", x, y); } Message::Write(text) => println!(\"Text: {}\", text), Message::ChangeColor(r, g, b) => { println!(\"Color: RGB({}, {}, {})\", r, g, b); } } }

Matching Tuples

fn describe_tuple(t: (i32, String, bool)) {
    match t {
        (0, s, _) => println!(\"First is zero, string: {}\", s),
        (n, _, true) => println!(\"First: {}, third is true\", n),
        (n, s, f) => println!(\"All parts: {}, {}, {}\", n, s, f),
    }
}

Matching Structs

struct Point {
    x: i32,
    y: i32,
}

fn describe_point(p: Point) {
    match p {
        Point { x: 0, y: 0 } => println!(\"Origin\"),
        Point { x, y: 0 } => println!(\"On x-axis at {}\", x),
        Point { x: 0, y } => println!(\"On y-axis at {}\", y),
        Point { x, y } => println!(\"At ({}, {})\", x, y),
    }
}

Catch-All with Underscore

fn demo(value: i32) {
    match value {
        1 => println!(\"One\"),
        3 => println!(\"Three\"),
        5 => println!(\"Five\"),
        _ => println!(\"Something else\"),  // Catch-all
    }
}

If Let for Simple Cases

When matching only one pattern:

let config_max = Some(3u8);

// Verbose match
match config_max {
    Some(max) => println!(\"Max: {}\", max),
    _ => (),
}

// Concise if let
if let Some(max) = config_max {
    println!(\"Max: {}\", max);
}

While Let

Continue looping while a pattern matches:

let mut stack = vec![1, 2, 3];

while let Some(top) = stack.pop() {
    println!(\"Popped: {}\", top);
}

Guard Conditions

Add conditions to patterns:

fn describe_value(value: i32) {
    match value {
        n if n < 0 => println!(\"Negative: {}\", n),
        n if n == 0 => println!(\"Zero\"),
        n if n % 2 == 0 => println!(\"Even: {}\", n),
        _ => println!(\"Odd positive\"),
    }
}

Combining Patterns

Multiple patterns in one arm:

fn demo(value: i32) {
    match value {
        1 | 3 | 5 => println!(\"Odd single digit\"),
        2 | 4 | 6 => println!(\"Even single digit\"),
        _ => println!(\"Something else\"),
    }
}

Range Patterns

fn demo(value: i32) {
    match value {
        1..=5 => println!(\"One through five\"),
        6..=10 => println!(\"Six through ten\"),
        _ => println!(\"Other\"),
    }
}

Practical Example

struct User {
    name: String,
    age: u32,
}

fn categorize_user(user: Option<User>) {
    match user {
        Some(User { name, age }) if age >= 18 => {
            println!(\"{} is an adult\", name);
        }
        Some(User { name, age }) => {
            println!(\"{} is a minor ({})\", name, age);
        }
        None => println!(\"No user\"),
    }
}

Pattern Matching Benefits

  1. Exhaustiveness: Compiler ensures all cases handled
  2. Safety: Can't access wrong fields by mistake
  3. Expressiveness: Complex logic becomes readable
  4. Type safety: Pattern matching respects types
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
Previous lessonEnumsContinue to lesson 16Collections: VecBack to Rust Fundamentals curriculum