Rust – if let Statement
Last Updated :
08 Sep, 2022
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
fn main() {
let gfg = ( "Geeks" , "for" , "Geeks" );
if let ( "Geeks" , "for" , "Geeks" ) = gfg {
println!( "Pattern matched with scrutinee expression" );
} else {
println!( "Pattern does not match" );
}
}
|
Output:
If the first value matches, Rust can guess the second and third values respectively.
Rust
fn main() {
let gfg = ( "Geeks" , "For" , "Geeks" );
if let ( "Geeks" , f, g) = gfg{
println!( "The values after writing the first value: {}, {}" ,f, g);
} else {
println!( "Pattern does not match" );
}
}
|
Output:
Example 2:
Rust
fn main() {
let gfg = ( "Geeksfor" , "Geeks" );
if let ( "Geeks" , f ) = gfg {
println!( "Course is {}" , f);
} else {
println!( "Pattern is unmatched" );
}
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...