DEV Community

Ben Santora
Ben Santora

Posted on

Rust - Conditions and Control Flow

Introduction

In this article, we'll explore the concepts of conditions and control flow in Rust, focusing on how Rust handles if, else if, and else statements, along with compound conditions using logical operators. Understanding these concepts is crucial for writing efficient and logical Rust programs.

Basic Conditions in Rust

A condition in Rust is any expression that evaluates to either true or false. These expressions are usually built using comparison operators, which compare values or variables. The primary comparison operators in Rust include:

  • < (less than)
  • > (greater than)
  • <= (less than or equal to)
  • >= (greater than or equal to)
  • == (equal to)
  • != (not equal to)

For example:



let condition = 2 < 3; // This will evaluate to `true`


Enter fullscreen mode Exit fullscreen mode

This creates a simple condition that evaluates whether 2 is less than 3. In this case, condition will hold the value true.

Type Comparisons

In Rust, it is important to compare values of the same type. Comparing different types, such as an integer and a floating-point number, can result in a compile-time error. Rust enforces strict type checking to avoid potential errors at runtime. For example, the following comparison would cause an error:



let condition = 2 < 2.5; // Error: Cannot compare integer with float


Enter fullscreen mode Exit fullscreen mode

To fix this, you can convert the integer to a float:



let condition = (2 as f32) < 2.5; // This will evaluate to `true`


Enter fullscreen mode Exit fullscreen mode

This ensures both values are of the same type before comparison.

Compound Conditions

Rust supports compound conditions using logical operators, allowing multiple conditions to be combined into a single expression. The three main logical operators in Rust are:

  • && (and) – True if both conditions are true.
  • || (or) – True if either condition is true.
  • ! (not) – Negates the condition, making true become false and vice versa.

Example:



let condition = (2 < 3) && (4 > 1); // True if both conditions are true


Enter fullscreen mode Exit fullscreen mode

In this case, both 2 < 3 and 4 > 1 are true, so the overall condition evaluates to true.

Control Flow with if, else if, and else

Rust allows developers to control the flow of their programs using if, else if, and else statements. These statements allow the program to make decisions based on conditions and execute different code blocks accordingly.

The if Statement

An if statement in Rust checks whether a condition is true and executes the code inside the block if it is:



let food = "cookie";
if food == "cookie" {
    println!("I like cookies too!");
}


Enter fullscreen mode Exit fullscreen mode

In this example, if food equals "cookie", the message "I like cookies too!" will be printed.

The else if Statement

The else if statement is used to check another condition if the initial if condition is false:



let food = "fruit";
if food == "cookie" {
    println!("I like cookies too!");
} else if food == "fruit" {
    println!("That sounds healthy!");
}


Enter fullscreen mode Exit fullscreen mode

Here, if the food is not "cookie", but instead "fruit", the program will print "That sounds healthy!"

The else Statement

The else statement is executed if all previous if and else if conditions are false:



let food = "bread";
if food == "cookie" {
    println!("I like cookies too!");
} else if food == "fruit" {
    println!("That sounds healthy!");
} else {
    println!("That sounds boring.");
}


Enter fullscreen mode Exit fullscreen mode

In this example, since the food is neither "cookie" nor "fruit", the program defaults to printing "That sounds boring."

Operator Precedence

When working with compound conditions, it's important to understand operator precedence. Rust evaluates not (!) first, followed by and (&&), and finally or (||). This precedence determines the order in which the conditions are evaluated unless parentheses are used to change it.

Example:



let condition = true || false && !false;


Enter fullscreen mode Exit fullscreen mode

In this case, !false is evaluated first, followed by false && true, and finally true || false, resulting in true. Using parentheses can change the precedence:



let condition = (true || false) && !false;


Enter fullscreen mode Exit fullscreen mode

Now the || operator is evaluated first, followed by the &&, resulting in true.

Conclusion

Control flow and conditions are essential for decision-making in Rust programs. By using if, else if, else, and compound conditions, you can write flexible and powerful Rust code. Understanding operator precedence is also key to ensuring your conditions evaluate as expected. Rust’s strict type system and logical operator support allow for safe and efficient programming.

Top comments (0)