
Basic Syntax
Below is a simple example demonstrating the basic syntax of the match statement. You specify the value to evaluate after the keywordmatch and then define a series of arms. Each arm consists of a pattern followed by a block of code that executes if the match is successful:
Example: Matching a Number
In this example, a number is compared against several specific patterns, with a default case to handle all other values:Using the OR Operator
Rust allows you to match multiple patterns for a single arm by using the OR operator (|). This feature makes it simple to execute the same block of code for multiple specific values:
Matching Value Ranges
A useful feature of Rust’s match statement is the ability to match ranges of values using the..= syntax. This allows you to check if a value falls within a specific range:
Destructuring Complex Data Types
Rust’s match statement is not limited to simple values. It also supports destructuring of complex data types like tuples, structs, and enums, enabling you to work with their individual components efficiently.Destructuring a Tuple
The following example demonstrates how to destructure a tuple and add conditional extractions with additional logic:(2, -2), the second arm is executed because the numbers are opposites.
Ignoring Unneeded Values
Sometimes you may only need part of the data from a tuple. In such cases, you can use the wildcard_ to ignore the parts that are not required:
Rust’s match statement ensures that all cases are covered at compile time, providing a safeguard against unexpected values.
Summary
Pattern matching with the match statement in Rust provides a flexible and elegant way to handle decision-making in your code. In this article, we covered:- The basic structure of a match statement for comparing a value against multiple patterns.
- Using the OR operator (
|) to handle multiple patterns in a single arm. - Matching ranges of values with the
..=syntax. - Destructuring complex data types such as tuples and selectively ignoring parts of a pattern.
