Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

if let
expression
if
rust

If expression in Rust

Educative Answers Team

When writing a computer program, we often want it to execute different actions for different scenarios and conditions.

In Rust, this is where the if expression comes in. Let’s have a look at what the if expression is.

Syntax

The form of an if expression is a condition, followed by a block of code; there can be an else expression with this block of code. See the syntax below for a basic if expression in Rust:

if expression {
    /* block of code in case expression
       is TRUE */
} else {
    /* block of code in case expression
       is FALSE */
}

Code

Let’s consider a simple example where we have to determine which number is greater out of the integer variables a and b. The code snippet below illustrates how this can be done using an if expression in Rust:

fn main() {
  let a = 50;
  let b = 20;

  if a > b {
    // condition is TRUE
    println!("a is greater than b")
  } else {
    // condition is FALSE
    println!("a is less than b")
  }
}

The code above follows the process flow below:

if-else Flowchart
1 of 5

RELATED TAGS

if let
expression
if
rust
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring