How to Use the Match Statement In Rust?

13 minutes read

The match statement is a powerful control flow construct in Rust that allows you to match the value of an expression against a set of patterns and execute the corresponding code block based on the match.


Here's how you can use the match statement in Rust:

  1. Write the match statement followed by the expression you want to match against.
  2. Use the => operator to separate the pattern from the code to be executed.
  3. Specify the patterns and the corresponding code blocks for each possible match, separated by commas.
  4. The patterns can be literals, variables, wildcards (_), or even complex structures.
  5. The first matching pattern encountered will have its code block executed, and the match will exit.
  6. If no pattern matches the expression, you can use the _ pattern as a catch-all (similar to a default case).


Here's an example that demonstrates the usage of the match statement in Rust:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fn main() {
    let number = 5;

    match number {
        1 => println!("One"),
        2 => println!("Two"),
        3 | 4 => println!("Three or Four"),
        5..=10 => println!("Between 5 and 10"), // Range pattern
        _ => println!("Something else"),
    }
}


In this example, we have an integer number that we want to match against various patterns. If number is 1, 2, 3, or 4, the corresponding code blocks will be executed. If number is between 5 and 10 (inclusive), the code block for the range pattern will be executed. If none of these patterns match, the catch-all pattern (_) will be used.


The match statement provides a concise and expressive way to handle different cases based on the value of an expression in Rust. It is commonly used in Rust code for tasks such as error handling, parsing, and pattern matching.

Top Rated Rust Books of July 2024

1
Programming Rust: Fast, Safe Systems Development

Rating is 5 out of 5

Programming Rust: Fast, Safe Systems Development

2
Rust in Action

Rating is 4.9 out of 5

Rust in Action

3
Programming Rust: Fast, Safe Systems Development

Rating is 4.8 out of 5

Programming Rust: Fast, Safe Systems Development

4
Hands-On Microservices with Rust: Build, test, and deploy scalable and reactive microservices with Rust 2018

Rating is 4.7 out of 5

Hands-On Microservices with Rust: Build, test, and deploy scalable and reactive microservices with Rust 2018

5
Programming WebAssembly with Rust: Unified Development for Web, Mobile, and Embedded Applications

Rating is 4.6 out of 5

Programming WebAssembly with Rust: Unified Development for Web, Mobile, and Embedded Applications

6
Rust for Rustaceans: Idiomatic Programming for Experienced Developers

Rating is 4.5 out of 5

Rust for Rustaceans: Idiomatic Programming for Experienced Developers

7
The Complete Rust Programming Reference Guide: Design, develop, and deploy effective software systems using the advanced constructs of Rust

Rating is 4.4 out of 5

The Complete Rust Programming Reference Guide: Design, develop, and deploy effective software systems using the advanced constructs of Rust

8
Beginning Rust Programming

Rating is 4.3 out of 5

Beginning Rust Programming

9
Beginning Rust: From Novice to Professional

Rating is 4.2 out of 5

Beginning Rust: From Novice to Professional

10
Systems Programming with Rust: A Project-Based Primer

Rating is 4.1 out of 5

Systems Programming with Rust: A Project-Based Primer


How to handle multiple patterns and conditions in a single match statement in Rust?

In Rust, you can handle multiple patterns and conditions in a single match statement by using pattern matching syntax and the if guard. Here is an example:

1
2
3
4
5
6
7
8
9
fn main() {
    let number = 7;

    match number {
        1 | 2 | 3 => println!("Number is between 1 and 3"),
        4..=10 if number % 2 == 0 => println!("Number is even between 4 and 10"),
        _ => println!("Number does not match any condition"),
    }
}


In this example, the match statement is used to compare the value of number with different patterns and conditions.

  • The pattern 1 | 2 | 3 matches if number is equal to 1, 2, or 3.
  • The pattern 4..=10 matches if number is between 4 and 10 (both endpoints included).
  • The condition number % 2 == 0 checks if number is even.
  • The _ pattern is a catch-all pattern that matches anything.


If number matches the first pattern, the corresponding code block will be executed. Otherwise, if number matches the second pattern and the condition is true, the second code block will be executed. If number doesn't match any pattern, the default code block will be executed.


How to use the match statement in Rust?

In Rust, the match statement is used for pattern matching. It allows you to compare the value of an expression against a series of patterns and execute the corresponding code block based on the matched pattern. Here's how you can use the match statement in Rust:

  1. Start by defining the expression you want to match. This can be a variable, function call, or any other expression.
1
let value = 42;


  1. Use the match keyword followed by the expression you want to match and a set of arms enclosed in curly braces {}. Each arm consists of a pattern and the code block to execute if the pattern matches.
1
2
3
4
5
6
match value {
    pattern1 => { /* code to execute if pattern1 matches */ },
    pattern2 => { /* code to execute if pattern2 matches */ },
    pattern3 if guard => { /* code to execute if pattern3 matches and guard condition is true */ },
    _ => { /* code to execute if no patterns match */ },
}


  1. Patterns can take various forms such as literal values, variables, wildcard _ for any value, or destructuring complex data structures like tuples and structs. The order of the arms matters, as the first matching pattern will be executed.
  2. You can include a guard condition using the if keyword after the pattern. The guard condition is an additional expression that must evaluate to true for the arm to match.


Here's a complete example that demonstrates the usage of the match statement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fn main() {
    let value = 42;

    match value {
        0 => println!("Value is zero"),
        1..=10 => println!("Value is between 1 and 10"),
        pattern @ 11 | pattern @ 13 => println!("Value is either 11 or 13: {}", pattern),
        pattern if pattern % 2 == 0 => println!("Value is an even number: {}", pattern),
        _ => println!("Value doesn't match any pattern"),
    }
}


In this example, different patterns are used to match against the value of the variable value. The matched pattern's code block is executed accordingly.


How to match specific values in Rust using the match statement?

To match specific values in Rust using the match statement, you can follow these steps:

  1. Create a variable or expression that you want to match against some specific values.
  2. Use the match keyword followed by the variable or expression you want to match.
  3. Write different match arms with the patterns you want to match.
  4. For each pattern, specify the code that should execute when the value matches the pattern.
  5. Optionally, you can include a _ pattern as the last arm to handle any unmatched values.


Here's an example that demonstrates how to match specific values in Rust:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fn main() {
    let number = 7;

    match number {
        1 => println!("The number is one"),
        3 | 5 | 7 => println!("The number is either three, five, or seven"),
        10..=20 => println!("The number is between ten and twenty (inclusive)"),
        _ => println!("The number does not match any specific value"),
    }
}


In this example:

  • The first match arm matches the value 1 and prints a corresponding message.
  • The second match arm uses the | operator to match the values 3, 5, or 7 and prints a message accordingly.
  • The third match arm uses the ..= operator to match any number between 10 and 20 (inclusive) and prints a message.
  • The final _ pattern acts as a catch-all for any unmatched values and prints a generic message.


When you run this code, it will produce the following output:

1
The number is either three, five, or seven


Feel free to modify the patterns and corresponding behavior according to your specific needs.


How to use the match statement to match and extract values in Rust?

In Rust, the match statement allows you to pattern match on different expressions and perform specific actions based on the matched patterns. It can be used to extract values from different data structures. Here's how you can use it to match and extract values:

  1. Start by defining the data structure you want to match on. For this example, let's assume we have a struct called User with two fields: name and age.
1
2
3
4
struct User {
    name: String,
    age: u32,
}


  1. Create an instance of the User struct.
1
2
3
4
let user = User {
    name: String::from("Alice"),
    age: 25,
};


  1. Use the match statement to match and extract the values from the User struct.
1
2
3
4
5
6
match user {
    User { name, age } => {
        println!("Name: {:?}", name);
        println!("Age: {:?}", age);
    }
}


  1. Inside the match arm, you destructure the User struct and bind its fields (name and age) to variables. You can then use these variables to perform actions.


This will print:

1
2
Name: "Alice"
Age: 25


You can also use patterns with placeholders (_) if you're only interested in extracting specific fields and not others. For example, if you only want to extract the name field:

1
2
3
4
5
match user {
    User { name, .. } => {
        println!("Name: {:?}", name);
    }
}


Here, the .. pattern ignores the age field.


Note: It's important to cover all possible cases in the match statement. You can use the _ pattern to handle any remaining cases or explicitly match specific patterns.


This is a basic example, but the match statement can handle much more complex patterns and data structures.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

Pattern matching in Rust is a powerful feature that allows you to match and destructure data structures such as enums, structs, tuples, and slices. It is primarily used in match expressions, function and closure arguments, and the let statement.To use pattern ...
To compile a Rust program, you first need to make sure that you have Rust installed on your system. You can check if Rust is installed by running the command rustc --version in your terminal. If Rust is not installed, you can download and install it from the o...
To match an IP host from a Rust URL, you can use a combination of regular expressions and string manipulation. First, extract the hostname part of the URL using a library like url::Url in Rust. Then, use a regular expression to match only the IP address from t...