Rust If Let

Authors

Rust If Let

Rust's if let expression enables you to compare an expression to a predetermined pattern. Contrast this with the if expression, which executes when a condition is true. You can define a pattern to be compared against an expression by using the let keyword. We run the if block if the expression matches the pattern; otherwise, we run the otherwise block.

Let's look at how to use the if let expression in Rust.

Syntax

if let pattern = expression {
    // true
} else {
    // false
}

Let's now look at an example of Rust If Let.

If Let Example

fn main() {
    let lang = "Rust";

    if let "Rust" = lang {
        println!("Rust Language")
    } else if let "Python" = lang {
        println!("Python Language");
    }
}

In the example above, we have a variable lang that holds the string “Rust”. We then use the if let expression to check for a specific pattern.

If the value is “Rust”, we execute the block inside the if let block. Otherwise, run the else if let block.

Output

Rust Language
TrackingJoy