Rust – if let Statement
If-let statement in Rust is an expression that allows pattern matching and is similar to an if expression. Once the pattern condition is matched then the block of code is executed.
A scrutinee is an expression that is matched during match statement executions.
For example match g{ X =>5 , Y => 10}, the expression g is the scrutinee.
Syntax:
If let (Value 1, Value 2) = match_expression
{
statement 1;
}
else
{
statement 2;
}
Pattern matching refers to checking whether the defined pattern has a number of values as scrutinee expression.
First of all, in this syntax, there is a definite pattern that is enclosed in the brackets. Rust checks whether the pattern matches the scrutinee expression (i.e. the match_expression). Only then, does the if let block gets executed, or if the pattern does not match the else block gets executed.
Example 1:
Rust
// Rust Program When Pattern is Matched fn main() { // define a scrutinee expression let gfg = ( "Beginner" , "for" , "Beginner" ); // pattern matches with the scrutinee expression if let ( "Beginner" , "for" , "Beginner" ) = gfg { println!( "Pattern matched with scrutinee expression" ); } else { // do not execute this block println!( "Pattern does not match" ); } } |
Output:
If the first value matches, Rust can guess the second and third values respectively.
Rust
// Rust program for matching fn main() { // defining a scrutinee expression let gfg = ( "Beginner" , "For" , "Beginner" ); // Checking if pattern matches with the scrutinee expression if let ( "Beginner" , f, g) = gfg{ println!( "The values after writing the first value: {}, {}" ,f, g); } else { // Block not executed println!( "Pattern does not match" ); } } |
Output:
Example 2:
Rust
// Rust program when the Pattern is not Matched fn main() { // defining a scrutinee expression let gfg = ( "Beginnerfor" , "Beginner" ); if let ( "Beginner" , f ) = gfg { println!( "Course is {}" , f); } else { // executing this block println!( "Pattern is unmatched" ); } } |
Output:
Contact Us