Trusted answers to developer questions

How to use the match operator in Rust

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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.

Code

Example 1

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 Summer
0 => println!("Summer"),
// If the input is 1, print Winter
1 => println!("Winter"),
// If the input is 2, print Autumn
2 => println!("Autumn"),
// If the input is 3, print Spring
3 => println!("Spring"),
// If input does not match 0, 1, 2 or 3, print
// invalid input
_ => println!("Invalid input")
}
}

Example 2

In match, multiple things can be matched against a single statement:

fn main() {
let input = 4;
match input {
// If the input is 0, print Summer
0 => println!("Summer"),
// If the input is 1, print Winter
1 => println!("Winter"),
// If the input is 2, print Autumn
2 => println!("Autumn"),
// If the input is 3 or 4, print Spring
3 | 4 => println!("Spring"),
// If input does not match 0, 1, 2, 3 or 4, print
// invalid input
_ => println!("Invalid input")
}
}

Example 3

The following code shows how you can match against ranges:

fn main() {
let input = 19;
match input {
// If the input is 0, print Summer
0 => println!("Summer"),
// If the input is 1, print Winter
1 => println!("Winter"),
// If the input is between 2 and 20 (both inclusive), print Autumn
2...20 => println!("Autumn"),
// If the input is 21, print Spring
21 => 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.

RELATED TAGS

rust
match
conditional
operator
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?