Rust if Expression

Rust language if Expression

In Rust, an if expression allows code to be branched based on a condition or set of conditions.

An if expression evaluates the truthiness of a statement. In other words, it determines whether a statement is true or false.

The code inside the if statement block will run if the statement is true. If the statement is false, then the code block will be skipped.

In this article, we cover general concepts and syntax of if expressions, more complex expressions using else, else if, and nested if expressions, as well as shorthand if expressions.

Overview of if Expressions in Rust

Let’s look at an example:

let fav_color = "Green";

if fav_color == "Green" {
    println!("Your favorite color is green!")
} 

The if expression in this example checks if the variable fav_color is equal to “Green” using the == comparison operator. Since this is true, this code will print out the line “Your favorite color is green!”.

If fav_color was a different color then the code block inside the if expression would not have executed.

Note that if expressions rely on comparison operators in order to function. The following table shows the comparison operators available in Rust:

Rust Comparison Operators

OperatorOperationSyntaxFunction
>Greater thana > bTrue if a is greater than b
<Lesser thana < bTrue if a is less than b
==Equal toa == bTrue if a is equal to b
>=Greater than or equal toa >= bTrue if a is greater than or equal to b
<=Lesser than or equal toa <= bTrue if a is less than or equal to b
!=Not equal toa != bTrue if a is not equal to b

Types of if Expressions in Rust

An if expression is a type of conditional expression. Conditional expressions, including if expressions, are used for control flow. The term control flow means using constructs like conditional expressions and loops to dictate (control) how code gets executed.

There are several types of if expressions in Rust, which give us more options to support control flow. These include:

  • if…else
  • if…else if…else
  • nested if expressions

We’ll cover each type in detail, building in complexity as we go through the different if expressions.

if…else

The if…else expressions allows us to execute one block of code if a condition is true, and a different block of code if the condition is not true.

An if…else expression is identical to an if expression, but it uses the else keyword in order to define a second block of code that will only execute if the if block did not execute:

if cat_or_dog == "cat" {

    // This block executes only if cat_or_dog is equal to "cat"

}

else {

    // This block executes if cat_or_dog is not equal to "cat"

}

Note that the else block isn’t really adding an additional conditional statement. It’s using the existing if statement to separate the flow into two paths: one through the if block, and one through the else block.

The else block is catch-all statement that executes any time the if statement doesn’t.

if…else if…else

When there are more possibilites that need to be addressed, we can use additional ‘else if‘ expressions in between the ‘if’ and ‘else’ expressions:

An if…else if…else adds an additional conditional expression using the term else if. It is similar to elif or elseif constructs in other languages and allows for multiple sequential if statements to be evaluated.

if cat_or_dog == "cat" {

    // This block executes only if cat_or_dog is equal to "cat"

}

else if cat_or_dog == "dog" {

    // This block executes if cat_or_dog is equal to "dog"

}

else {

    // This block executes if cat_or_dog is not equal to "cat" or "dog"

}

Multiple else if blocks can be stacked, allowing for complex branching options.

Nested if Expressions

When one if expression is located within another, the configuration is referred to as a nested if expression. Nested if expressions allow the creation of more complex patterns.

if cat_or_dog == "cat" {
    
    if breed== "Siamese" {

        println!("Siamese cats are the cutest!");
    }

    else {

        println!("We like {} cats too!", breed);

    }

}

Nested if expressions can often be replaced by checking multiple conditions using the && operator:

if cat_or_dog == "cat" && breed == "Siamese" {
   
    println!("Siamese cats are the cutest!");

}

This example is much cleaner and more efficient, but is more limited in the responses it can give.

if Expression Shorthand

Rust includes a shorthand syntax that allows us to write an if expression in a single line of code.

The if expression shorthand sets the entire expression inside a variable. The if expression is evaluated when the variable is called.

The general shorthand syntax is:

let <variable_name> = if <condition> {} else {}

For example:

let cat_or_dog = if my_pet == "cat" {println!("You have a cat!")};