Conditions and Control Flow

danielmwandiki

Daniel

Posted on July 16, 2024

Conditions and Control Flow

One of the most common tasks when writing code is to check whether certain conditions are trueor false.

if Expressions

An if expression allows you to branch your code depending on conditions. You provide a condition and then state, “If this condition is met, run this code block. Do not run this code block if the condition is not met.”

Using only if block:
let age = 13;

if age < 18 {
    println!("Hello, child!"); 
}
Enter fullscreen mode Exit fullscreen mode

It’s also worth noting that the condition in this code must be a bool. We'll get an error if the condition isn’t a bool.

Using if and else blocks:
fn main() {
    let a = 36;
    let b = 25;

    if a > b {
        println!("a is greater than b");
    } else {
        println!("b is greater than a");
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, I have declared two integer variables, a and b, with the values '36' and '25'. On line 5, I check if the value stored in the variable a is greater than in variable b. If the condition is evaluated as true, the code on line 6 will be executed. If the condition evaluates to false, because we have an else block (which is optional), the code on line 8 will get executed.

Using else if conditional:
fn main() {
    let team_size = 7;
    let team_size_in_text;

    if team_size < 5 {
        team_size_in_text = "Small";
    } else if team_size < 10 {
        team_size_in_text = "Medium";
    } else {
        team_size_in_text = "Large";
    }

    println!("Current team size : {}", team_size_in_text);
}

Enter fullscreen mode Exit fullscreen mode

In this code, we define a variable team_size with a value of 7. We also declared team_size_in_text, but it has not been initialized yet. The first if statement checks if team_size is less than 5. If true, team_size_in_text is set to Small. The else if statement checks if team_size is less than 10. Since team_size is 7, which is less than 10, team_size_in_text is set to Medium. The final else block would execute if neither of the previous conditions was true, setting team_size_in_text to Large.

Using if in a let Statement:

Because if is an expression, we can use it on the right side of a let statement to assign the outcome to a variable. If the types are mismatched, we’ll get an error.

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };

    println!("The value of number is: {number}");
}
Enter fullscreen mode Exit fullscreen mode

Using Loops

The Rust programming language has three different loops based on what you want to achieve and what is available:

  • for
  • while
  • loop
for loop

The for loop is primarily used to iterate over an iterator. This iterator can be made from anything, from an array, a vector, a range of values, or anything custom.
Here is an example:

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a {
        println!("the value is: {element}");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code, I declare an array a with 5 elements. The for loop iterates over each element in the array a and prints its value.

while loop

A program will often need to evaluate a condition within a loop. While the condition is true, the loop runs. When the condition ceases to be true, the program calls break, stopping the loop. It’s possible to implement behavior like this using a combination of loop, if, else, and break. The while loop stops only when the loop has completed the execution of all statements in the current iteration, and upon checking the condition, it is evaluated as false.
Here is an example:

fn main() {
    let mut var = 0;

    while var < 3 {
        println!("{var}");
        var += 1;
    }
}
Enter fullscreen mode Exit fullscreen mode

I have a mutable variable, var, with an initial value of 0. The while loop will loop if the value stored in the mutable variable var is less than 3. Inside the loop, var's value gets printed, and later on, its value gets incremented by 1

loop

The loop keyword tells Rust to execute a block of code repeatedly forever or until you explicitly tell it to stop.
Here is an example:

fn main() {
    loop {
        println!("again!");
    }
}
Enter fullscreen mode Exit fullscreen mode

When we run this program, we’ll see again! printed over and over continuously until we stop the program manually. Most terminals support the keyboard shortcut ctrl-c to interrupt a program stuck in a continual loop.
To stop the execution of an infinite loop, the break keyword is used inside the loop.
Here is an example:

fn main() {
    let mut var = 0;

    loop {
        if var > 3 {
            break;
        }

        println!("{}", var);
        var += 1;
    }
}
Enter fullscreen mode Exit fullscreen mode

You have a mutable variable var with an initial value of 0. The infinite loop starts with an if condition that should var's value be greater than 3, the break keyword should be executed. Later on, var's value is printed to the stdout, and then its value is incremented by 1.

💖 💪 🙅 🚩
danielmwandiki
Daniel

Posted on July 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Conditions and Control Flow
rust Conditions and Control Flow

July 16, 2024

Rust Reference and Ownership
rust Rust Reference and Ownership

July 18, 2024