Open In App

Rust – if let Statement

Last Updated : 08 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 = ("Geeks", "for","Geeks");
    // pattern matches with the scrutinee expression
    if let ("Geeks", "for","Geeks") = 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 = ("Geeks", "For","Geeks");
    // Checking if pattern matches with the scrutinee expression
    if let ("Geeks", 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 = ("Geeksfor", "Geeks");
    
    if let ("Geeks", f ) = gfg {
        println!("Course is {}", f);
    } else {
        // executing this block
        println!("Pattern is unmatched");
    }
}


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads