Open In App

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 :

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")
    }
Syntax :
   let gfg = String::from("cp");
   
    // match operator
    match &*gfg {
        "ds"|"cp"|"fg" => println!("topics included in gfg"),
        _ => println!("Not in gfg topics")
    }
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 






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.






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.




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

Article Tags :