Skip to content
Related Articles

Related Articles

Improve Article
Rust – If let Operator
  • Last Updated : 15 Mar, 2021

The basic difference between conventional if-else and if let is that if let uses one pattern that needs to be matched to an expression also known as scrutinee, if the pattern matches the expression then the corresponding code is executed, or in most cases that value is assigned according to it.

Syntax :

let gfg=value;
let gfg_answer=if let value_1 = expression{
}
else if let value_2=expression{
}
...
else{
}  

Example 1: Program for if let operator in Rust.

  • In this example the value we will have one variable gfg=”algo” and we will check it against other values.
  • For the first condition here if the string “cp” equals to gfg variable then gfg_answer will be assigned the value dsa topic=cp because we used the concat method to adddsa topic=and cp“.
let gfg_answer=if let "cp" = gfg {
   concat!("dsa topic=","cp")
} 
  • If this condition is not met then it will check for other else if or else conditions.
  • The final step is to print the value of gfg_answer.

Rust




// Rust program for if let operator
fn main() {
    
// string created algo assigned to gfg
let gfg = "algo";
  
// using if let operator  
let gfg_answer = if let "cp" = gfg {
   concat!("dsa topic=","cp")
} else if let "ds" = gfg {
    concat!("dsa topic=","ds")
} else if let "algo" = gfg {
    concat!("dsa topic=","algo")
} else {
    concat!("dsa topic=","not in gfg")
};
    
// printing the gfg_answer variable
println!("{}",gfg_answer);
}

Output :



dsa topic=algo

Example 2 :

  • Here we will use gfg variable having value 10, and we will compare it to values and assign the variable gfg_answer according to it.
let gfg = Some(10);
let gfg_answer = if let Some(10) = gfg {
    11
}
  • And we will keep on checking the conditions until some condition is matched or last will be the else condition.
  • Finally, we will print the gfg_answer variable.

Below is the program for if let operator Rust.

Rust




// Rust program for if let operator
fn main() {
    
// gfg variable assigne value 10  
let gfg = Some(10);
  
// using if let operator  
let gfg_answer = if let Some(10) = gfg {
    11
} else if Some(20) == gfg {
    22
} else if let Some(30) = gfg {
    33
} else {
    -1
};
    
// printing the value 
println!("gfg_anser={}",gfg_answer );
}

Output :

gfg_answer=11



My Personal Notes arrow_drop_up
Recommended Articles
Page :