match
is a control flow operator in Rust that is used to transfer control to a particular block of code based on the value of the variable being tested. This operator is the equivalent of the switch statement in languages like C++, JavaScript, and Java.
The match
operator takes in a variable and compares its value with each case value. If there is a match, the corresponding block of code is executed.
Suppose that you want to display the season corresponding to the given input. Take a look at the code below to see how the match
operator would come in handy in this situation.
fn main() {let input = 2;match input {// If the input is 0, print Summer0 => println!("Summer"),// If the input is 1, print Winter1 => println!("Winter"),// If the input is 2, print Autumn2 => println!("Autumn"),// If the input is 3, print Spring3 => println!("Spring"),// If input does not match 0, 1, 2 or 3, print// invalid input_ => println!("Invalid input")}}
In match
, multiple things can be matched against a single statement:
fn main() {let input = 4;match input {// If the input is 0, print Summer0 => println!("Summer"),// If the input is 1, print Winter1 => println!("Winter"),// If the input is 2, print Autumn2 => println!("Autumn"),// If the input is 3 or 4, print Spring3 | 4 => println!("Spring"),// If input does not match 0, 1, 2, 3 or 4, print// invalid input_ => println!("Invalid input")}}
The following code shows how you can match against ranges:
fn main() {let input = 19;match input {// If the input is 0, print Summer0 => println!("Summer"),// If the input is 1, print Winter1 => println!("Winter"),// If the input is between 2 and 20 (both inclusive), print Autumn2...20 => println!("Autumn"),// If the input is 21, print Spring21 => println!("Spring"),// If input does not fall between 0 and 21 (both inclusive), print// invalid input_ => println!("Invalid input")}}
Remember,
match
is not restricted to numeric data types. Other data types like string and boolean can also be used. For more details, refer to the official documentation.
Free Resources