Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Exhaustive Pattern Matching with `match` and `if let`

Recommended resources

Welcome back! In our previous lesson, we established how to define custom data types using structs and enums. We saw that while structs group data where all fields exist together, enums define a type that can be one of several possible variants, each potentially holding different data. We concluded with a key question: once we have an enum value, how do we write code that behaves differently based on which variant it is?

This lesson will answer that question by introducing you to Rust's powerful control flow constructs for pattern matching: match and if let. You'll learn how match allows you to compare a value against a series of patterns and execute code based on which pattern it "fits." We'll see how this goes far beyond the capabilities of a switch statement in C++. We will then explore if let as a concise tool for situations where you only need to match a single pattern.

The match Control Flow Construct

The match construct is one of Rust's most beloved features. It allows you to take a value and compare it against a sequence of "patterns." When it finds a pattern that the value matches, it runs the code associated with that pattern.

The official Rust book provides a great mental model for this: think of a coin-sorting machine where a coin drops through the first hole it fits into.

The match Control Flow Construct

This first section from "The Rust Programming Language" book introduces the core idea behind match.

Please read the introductory part of the chapter, from the beginning down to the subsection "Patterns That Bind to Values". Focus on the coin-sorting analogy and the basic structure of a match expression with its "arms" (pattern => code).

As you read, you may have noticed that match looks similar to the switch statement from C/C++. There are some crucial differences that make match significantly more powerful and safe.

Understanding Rust as a C++ developer

This article from DEV Community directly compares Rust's control flow to C++, which should feel familiar.

Focus on the section under the heading "Control flow — conditions and loop". Pay attention to the side-by-side comparison of a C++ switch and a Rust match. Note the absence of "fall through" and the use of the _ wildcard.

The most important difference highlighted in that article is exhaustiveness. The Rust compiler enforces that you handle every single possible case for the type you are matching on. If you forget a case, your code will not compile. This is a powerful safety guarantee that eliminates a whole class of bugs common with switch statements in other languages.

Let's see this in action with the Option enum from our last lesson.

The match Control Flow Construct

Let's return to the Rust book to see a concrete example of the exhaustiveness rule.

Read the section titled "Matches Are Exhaustive". Notice how the compiler provides a very helpful error message when the None case is not handled, preventing a potential null-pointer-style bug at runtime.

This compile-time check is a cornerstone of Rust's reliability. The compiler won't let you forget to handle the None case, forcing you to write more robust code.


Pattern Matching on Enum Data

The real power of match shines when you combine it with enums that carry data. A match arm can not only check for a specific enum variant but also destructure it, binding the data it contains to variables that you can use in that arm's code.

The match Control Flow Construct

These next two sections of the Rust book demonstrate how to extract data from enum variants.

First, read "Patterns That Bind to Values". The Coin::Quarter(state) example clearly shows how the state variable is created and bound to the data inside the Quarter variant. Then, read the section on matching Option<T>. The plus_one function is a classic example of handling both the Some(i) case (by binding the inner value to i) and the None case.

Let's reinforce these concepts with a video walkthrough.

Enums and Pattern Matching in Rust

This segment from the "Let's Get Rusty" channel on YouTube provides a great visual explanation of pattern matching with enums, covering data binding and exhaustiveness.

Watch the part of the video covering the match expression, from this timestamp. It covers the Coin and plus_one examples and also introduces the _ placeholder, which we'll discuss next.

In the last lesson, we saw a conceptual diagram of how an enum can be a refactoring of multiple structs. Now, we can see how match completes that picture. Instead of needing different functions to handle different struct types (perhaps using a C-style function pointer table), Rust lets you handle all variants of a single enum type in one place with compile-time checks.

This image compares a Rust `enum` and `match` expression on the left with a C-style implementation using function pointers for dispatch on the right. The Rust version is not only more readable but also safer, as the compiler guarantees all `Message` variants are handled.

Catch-All Patterns and if let

What if you don't want to handle every single enum variant explicitly? For example, you might only care about one or two specific cases and want to do a default action for all others. For this, match provides catch-all patterns.

The match Control Flow Construct

This final section on match from the Rust book explains how to handle "the rest" of the cases without listing them all.

Read the section on catch-all patterns. Pay attention to the difference between using a variable name like other to catch and use the value, versus using the _ placeholder to ignore it.

Using a catch-all is fine, but sometimes even a match expression can feel verbose if you only care about a single case. For these situations, Rust provides a handy shorthand: if let.

The if let syntax lets you combine an if and a let to match a value against a single pattern. If the pattern matches, the if block is executed. You can optionally add an else block to handle the case where the pattern does not match.

This diagram shows how an `if let` statement is syntactic sugar for a `match` expression that only has two arms: one for the pattern you care about and a catch-all `_` arm that does nothing.

This makes if let ideal for unwrapping a value from an Option or Result when you only intend to proceed if the value exists.

Rust Branching - if let, match

The video "Rust Branching - if let, match" from Code to the Moon has a great practical example of using if let.

Watch the section demonstrating if let with a Result type, from this segment. Notice how if let Ok(res) = ... both checks that the result is Ok and destructures the value into the res variable in one concise line.

So, when should you use match versus if let?

  • Use match when you need to handle multiple distinct patterns, and the compiler's exhaustiveness check is valuable to ensure you've covered all cases.
  • Use if let when you only care about one specific pattern and want to ignore all others. It's a more concise way to write a match that would otherwise have a single meaningful arm and a catch-all _ => {} arm.

Conclusion

In this lesson, you've learned how to act on the enum types we created previously. You now have a robust, compiler-verified way to control your program's flow based on the data it's processing.

Here are the key takeaways:

  • The match statement allows you to compare a value against a series of patterns and execute code based on the first pattern that matches.
  • Rust's match expressions are exhaustive, meaning the compiler forces you to account for every possible value, which prevents a large category of bugs.
  • Patterns in match arms can bind to data inside enum variants, allowing you to extract and use values in a safe way.
  • The _ placeholder is a catch-all pattern used to ignore values you don't need to use.
  • if let is a concise alternative to match for situations where you only care about matching one specific pattern and ignoring the rest.

We briefly saw if let being used with Result, Rust's primary tool for handling operations that can fail. In our next lesson, we will dive deep into error handling by exploring the Result enum in detail and learning how to use the powerful ? operator to write clean and idiomatic error-handling code.