Trusted answers to developer questions

If let expression in Rust

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

An if let expression in Rust is slightly different from an if expression in Rust. if let includes the let keyword followed by a pattern, a = sign, and an expression. If the expression matches the pattern, then the following block of code is executed. If ​it does not match, then ​the else block of code is executed.

svg viewer

Syntax

The syntax for the if let expression is: ​

if let PATTERN = EXPRESSION {
    /* block of code in case PATTERN MATCHES THE EXPRESSION
*/
} else {
     /* block of code in case PATTERN DOES NOT MATCH THE EXPRESSION
*/
}

Code

The code snippet below illustrates how the if let expression can be used in Rust:

fn main() {
let fruits = ("Apple", "Banana");
// Pattern does not match the expression because Orange
// is not part of fruits
if let ("Orange", y) = fruits {
println!("Orange is served with {}", y);
} else {
// So this piece of code executes instead.
println!("No Oranges available");
}
// Pattern matches the expression because Apple
// is part of fruits
if let ("Apple", y) = fruits {
println!("Apple is served with {}", y);
}
}

RELATED TAGS

if let
if
expression
rust
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?