Match Operator is a powerful operator which lets you match a particular value with a range of values and execute some operations or code for it. It is similar to switch() in Java.
Match Operator Keypoints :
- For checking for a group of values, where the value to be checked is “cp”.
Syntax :
let gfg = String::from("cp");
// match operator
match &*gfg {
"ds" => println!("Data Structure"),
"cp" => println!("Competitive programming"),
"fg" => println!("FAANG"),
_ => println!("not in GFG topics")
}
- For checking multiple conditions in one case here gfg value to be checked is “cp”.
Syntax :
let gfg = String::from("cp");
// match operator
match &*gfg {
"ds"|"cp"|"fg" => println!("topics included in gfg"),
_ => println!("Not in gfg topics")
}
- For checking a range of values from 2 to 100.
Syntax :
let gfg = 101;
// match operator
match gfg {
2..=100 => println!("between 2 to 100"),
_ => println!("either 1 or above 100"),
}
Example 1: Below is the Rust program for match operator having multiple cases
- Here we will use variable gfg to store string “cp” then we will use the match operator to match the given list options.
- If it is matched the option is printed accordingly and if no match found then the output will be “not in gfg topics”.
Rust
fn main() {
let gfg = String::from( "cp" );
match &*gfg {
"ds" => println!( "Data Structure" ),
"cp" => println!( "Competitive programming" ),
"fg" => println!( "FAANG" ),
_ => println!( "not in gfg topics" )
}
}
|
Output :
Competitive programming
Example 2: Below is the Rust program for match operator having multiple conditions in one case.
- Here we will use gfg variable to hold the string “cp” but now we will check multiple conditions using one case only.
- If it does not match in this condition then the output will be “Not in GFG topics”.
Rust
fn main() {
let gfg = String::from( "cp" );
match &*gfg {
"ds" | "cp" | "fg" => println!( "topics included in gfg" ),
_ => println!( "Not in GFG topics" )
}
}
|
Output :
topics included in gfg
Example 3: Below is the Rust program for match operator having a range of values.
- Here we will use the gfg variable having value 101, and now we will match values for a range of values in a condition.
- The condition for matching will be between 2 and 100 if it’s not in this range the output will be “either 1 or above 100”.
Rust
fn main() {
let gfg = 101;
match gfg {
2..=100 => println!( "between 2 to 100" ),
_ => println!( "either 1 or above 100" ),
}
}
|
Output :
either 1 or above 100
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!