Rust – Match Operator
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() { // create string variable gfg let gfg = String::from( "cp" ); // match with operator 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() { // gfg variable having value 101 let gfg = 101; // checking for value is between 2 to 100 or not match gfg { 2..=100 => println!( "between 2 to 100" ), _ => println!( "either 1 or above 100" ), } } |
Output :
either 1 or above 100
Please Login to comment...