Match in Rust

Introduction

A classic construct supported by most programming languages is switch-case which allows us to compare a value against a series of patterns. Rust also uses this concept but with a different name and different keyword, and that is a Match. In this article, we will learn about match keyword.

Match keyword in Rust

In Rust, the match keyword is used to compare or match a value against a series of patterns and then execute the code based on what pattern matches the value. Patterns can be made up of literals, variables, wildcards, and many other things.

In the match statement, we do not usually use a break keyword after each case, unlike in C, as in Rust, if a pattern gets matched, the program's control goes out of the match block, and it does not check conditions after that. So we need not use breaks here like in other programming languages.

Syntax

match variable{
    value1=> //value1 code to be executed
    value2=> //value2 code to be executed
    value3=> //value3 code to be executed
....
}

In the above syntax, the variable is matched with values like value1, value2, value3, and so on and executes the corresponding code.

Let's consider the following example to understand the match keyword better.

fn main(){
    let mut input = String::new();
    println!("Enter a number:");
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let choice: u64 = input.trim().parse().expect("Please enter a valid integer");
    match choice{
    1=> println!("Your choice is 1"),
    2=> println!("Your choice is 2"),
    3=> println!("Your choice is 3"), 
    _=> println!("Wrong choice"),
    }
}

Output

match case

In the above example, we created a mutable variable named input and took input from the user in the same variable. In the next line, we converted this input variable currently in the string data type to the i64 data type and stored it in the choice variable. Later, we matched that choice with a set of patterns we defined. If the user enters 1, it will print the line of code corresponding to it; if the user enters 2, it will print the line of code corresponding to it. If the user enters 3, it will print the line of code corresponding to it, and if the user enters anything else, the default case will be executed.

Matching values using the OR operator in Rust

We can also match the variable with multiple options in one statement when we want the same piece of code to be executed for multiple options. We can do these by using the OR operator.

For example

fn main() {
  let age = 18;
  match age {
    18 | 19 | 20 | 21 | 22 |23 | 24 | 25 => println!("Hi!"),
    _ => println!("Unreachable")
  }
}

Output

match case

In the above example, we have created a variable named age and assigned it some value which is 18. Then, we created a matching case for that variable, and for multiple cases 18, 19, 20, 21, 22, 23, 24, and 25, we executed the same set of statements or code, "Hi!". And for the default case, we have printed "Unreachable". This is very useful for cases where we have these kinds of situations.

Matching boolean cases in Rust

 There can be situations where we must match values to check true or false cases.

For example

fn main() {
  let condition =false;
  let active = match condition {
    false => 0,
    true => 1,
  };
  println!("Active: {}", active)
}

Output

match case

In the above example, we have created a boolean variable named condition and assigned false to it. Again, we created a variable named active which will store the return value of the match. In the match statement, we have two cases, false and true. If the value of the condition is false, it will match with false and return 0, and if the value of the condition is true, it will match with true and return 1. Later, we print the value of the active variable.

Matching values with a range in Rust

We can also use range in the match case. 

For example

fn main() {
  let age = 18;
  match age {
    18..=22 => println!("Hi!"),
    _ => println!("Unreachable")
  }
}

Output

match case

In the above example, we have created a variable named age and assigned 23 to it. In the next line, we created a match statement and will check the match based on the age variable. Inside the match, we created a pattern that will be matched if the age value is between the range of 18 to 22 and prints Hi! , and if other than that, it will be matched to the default case. Print Unreachable.

More about the match in Rust

  • Exhaustiveness- When using a match, you need to account for all the possibilities. If you forget to do this, Rust will remind you that everything is covered and nothing goes wrong unexpectedly.
  • Patterns- When using a match, you're looking for specific things that might happen with your input. You can use different ways to find these things, like specific values or ranges. The order you put them matters because Rust will go through them individually until it finds a match.
  • Ownership- When you use to match and find something, you might take responsibility for it. This means you can work with it but must be careful when using it outside of the match. Rust ensures you handle it correctly, so there aren't any problems. 
  • Binding- When you find something with matches, you can give it a name to use later. This is helpful when you want to look for things inside of other things or when you want to do different things based on what you found.
  • Guards- Sometimes, you must ensure that the thing you found meets certain conditions before you can use it. Guards let you do this by checking its size or other properties.

Conclusion

The match statement in Rust provides a powerful and concise way to perform pattern matching on values and control program flow based on those matches. It allows for precise and flexible handling of different scenarios or conditions, from handling specific input values to handling complex data structures.

The syntax is straightforward and easy to read, making it a popular choice for Rust programmers. Overall, the match statement is an essential tool in the Rust programming language that helps ensure code reliability and maintainability.


Similar Articles