Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

if let
if
expression
rust

If let expression in Rust

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring