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.
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
*/
}
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 fruitsif 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 fruitsif let ("Apple", y) = fruits {println!("Apple is served with {}", y);}}
RELATED TAGS