DEV Community

Cover image for HOW TO USE CONTROL FLOW IN THE RUST PROGRAMMING LANGUAGE
Rasheed Olaleye
Rasheed Olaleye

Posted on

HOW TO USE CONTROL FLOW IN THE RUST PROGRAMMING LANGUAGE

Easy steps to implement control flow for beginners

Just as decisions are crucial for individuals, in programming, a program also makes decisions based on specific conditions.

Prerequisite: Foundational programming knowledge

Table of contents

  1. What is Control Flow?
  2. Real-Life Examples of Control Flow
  3. Using IF Expressions
  4. Using Loop Expressions
  5. Using While Expressions
  6. Using For Expressions
  7. Peculiarities of Rust
  8. Conclusion

**

What is Control Flow?

**
Control flow refers to the sequence in which instructions or statements are executed in a program. It allows the program to make decisions and perform different actions based on specific conditions. By using control flow structures, such as conditional statements (e.g., if-else statements) and loops, programmers can create programs that can adapt and respond to different situations.

**

Real-Life Examples Of Control Flow

**
1.Alarm Clock: When you set an alarm for a specific time, it operates autonomously based on the condition. For instance, if you want to wake up at 4 am, the alarm will ring when the designated time is reached.
2.Traffic Light: Control flow is used in the context of traffic lights to decide which color light should be displayed at a specific time. Based on set standards and conditions, the control flow mechanism enables the sequential switching between the green, red, and yellow lights. This guarantees the orderly and secure passage of cars and people crossing the street at crossings.
3.ATMs(Automated Teller Machine): When you insert your ATM card into a machine, it performs a series of checks to verify your identity. One of these checks involves asking you to enter your PIN (Personal Identification Number). If the entered PIN matches the one associated with your card, the ATM grants you access to perform various actions, such as withdrawing cash, transferring funds, or conducting other banking transaction.

**

Using IF expression

**
An if expression can be used to branch your code depending on conditions. The structure is simple: if a condition is met, execute a block of code; if not, do not execute it. For example, throughout this article, we will be solving a problem of calculating the number of days using a control flow

fn main() {
    let day = "Tuesday";
    let num_days = if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
        day == "Thursday" || day == "Friday" {
            5
        } else if day == "Saturday" || day == "Sunday" {
            2
        } else {
            println!("Invalid day!");
            -1
        };

    println!("There are {} days in the week.", num_days)
}

Enter fullscreen mode Exit fullscreen mode

Before the IF statement, I declare a variable using the LETkeyword and initialize it to Tuesday, then I declare another variable num_days to hold the result of the conditions. I use a semicolon to end the statement which assigns value to a statement.

Try running this code, you would see, this
Note: cargo is a keyword in Rust used to execute a line of code just like npm in javascript

PS C:\Users\ELITEBOOK 840 G3\Rust\Practice> cargo run
warning: crate `Practice` should have a snake case name      
  |
  = help: convert the identifier to snake case: `practice`   
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning     
    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target\debug\Practice.exe`
There are 5 days in the week.
Enter fullscreen mode Exit fullscreen mode

Using Loop expression

Using a loop can sometimes be tricky or may seem somewhat unusual. However, when you need to iterate over an object in Rust, a loop may be a better choice. Let's explore this further.

fn main() {
    let day = "Tuesday";
    let mut num_days = -1;


    loop {
        if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
            day == "Thursday" || day == "Friday" {
                num_days = 5;
                break;
        } else if day == "Saturday" || day == "Sunday" {
                num_days = 2;
                break;
           } else {
                println!("Invalid day!");
                break;
            }
    }


    println!("There are {} days in the week.", num_days);
}


Enter fullscreen mode Exit fullscreen mode

The first code we wrote earlier used an IF statement. Once a condition is satisfied, the corresponding block of code is executed, and the control flow moves to the next block of code. In contrast, a LOOP continues indefinitely until a condition is met. This code is more concise than the IF statement.

Let's run the code again and see the output

cargo run
warning: crate `Practice` should have a snake case name      
  |
  = help: convert the identifier to snake case: `practice`   
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning     
    Finished dev [unoptimized + debuginfo] target(s) in 0.03s
     Running `target\debug\Practice.exe`
There are 5 days in the week
Enter fullscreen mode Exit fullscreen mode

Using While expression

While is executed when corresponding code is true.
let's check

  fn main() {
    let day = "Tuesday";
    let mut num_days = -1;


    while num_days == -1 {
        if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
            day == "Thursday" || day == "Friday" {
                num_days = 5;
        } else if day == "Saturday" || day == "Sunday" {
                num_days = 2;
        } else {
            println!("Invalid day!");
            break;
        }
    }


    println!("There are {} days in the week.", num_days);
}
Enter fullscreen mode Exit fullscreen mode

**

Using For Expression

**
The for expression in Rust is used to iterate over collections or ranges with known lengths.
It provides a convenient and concise way to loop over elements without explicitly managing indices .It is commonly used with arrays, vectors, strings, and other iterable types in Rust.
Examples of how to use For

*Examples of how to use For *

fn main() {
    let day = "Tuesday";
    let mut num_days = -1;


    for x in 0..1 {
        if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
            day == "Thursday" || day == "Friday" {
                num_days = 5;
        } else if day == "Saturday" || day == "Sunday" {
                num_days = 2;
        } else {
            println!("Invalid day!");
            break;
        }
    }


    println!("There are {} days in the week.", num_days);
}

Enter fullscreen mode Exit fullscreen mode

You can see that the code above is not different from the others we have written. For first check for the range between 0 to 1 before interaction started.

_
Let run and see the output_

cargo run
warning: crate `Practice` should have a snake case name      
  |
  = help: convert the identifier to snake case: `practice`   
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning     
    Finished dev [unoptimized + debuginfo] target(s) in 0.03s
     Running `target\debug\Practice.exe`
There are 5 days in the week
Enter fullscreen mode Exit fullscreen mode

We can also use it to iterate over array, vector, string.

Iterating over Array:

fn main() {
    let days = ["Monday", "Tuesday", "Wednesday", "Thursday"];

    for day in &days {
        println!("Day of the week: {}", day);
    }
}
Enter fullscreen mode Exit fullscreen mode

The code defines an array of the days of the week. It uses a for loop to print each day. The & means we're borrowing the array's values.

Let us run this code

cargo run
warning: crate `Practice` should have a snake case name
  |
  = help: convert the identifier to snake case: `practice`
  = note: `#[warn(non_snake_case)]` on by default

    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target\debug\Practice.exe`
Day of the week: Monday
Day of the week: Tuesday
Day of the week: Wednesday
Day of the week: Thursday
Enter fullscreen mode Exit fullscreen mode

Iterating over a vector:
A vector is a dynamic array that can store and change a variable number of elements of the same type. It’s represented by Vec, where T is the type of elements.

fn main() {
    let days = vec!["Monday", "Tuesday", "Wednesday", "Thursday"];

    for day in &days {
        println!("Day of the week: {}", day);
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above code created a vector of days using the vec! macro. The for loop then prints each day.

Iterating over a string:

String is combination of characters stored in memory. It is usually put in a quotation mark.String flour in Rust is called String.
for example
let a: String = String::from("Hello, World");


fn main() {
    let message = "Hello, Rust progamming language!";

for c in message.chars() {
    println!("Character: {}", c);
}

}

Enter fullscreen mode Exit fullscreen mode

Peculiarities of Rust Control flow

Here we are going to discuss the challenges in rust while using control flow. Every programming language has its peculiar challenges.

Let's use the examples below to learn one of the peculiarities of Rust


fn main() {
 let days = 10; 
if days { 
println!("days was three"); } }
Enter fullscreen mode Exit fullscreen mode

Here, we are going to discuss the challenges in Rust when using control flow. Every programming language has its own peculiar challenges.

   Compiling Practice v0.1.0 (C:\Users\ELITEBOOK 840 G3\Rust\Practice)
error[E0308]: mismatched types
 --> src\main.rs:3:7
  |
3 |    if days { 
  |       ^^^^ expected `bool`, found integer

Enter fullscreen mode Exit fullscreen mode

From the error messages displayed by the compiler, it expects a boolean value. This means that you must always include a boolean expression in your code when dealing with an integer.
Let's take a look at the correct code to better understand this

fn main () {
Let days = 10;
If days > 5{
println("days was three")
Enter fullscreen mode Exit fullscreen mode
cargo run
   Compiling Practice v0.1.0 (C:\Users\ELITEBOOK 840 G3\Rust\practice)
warning: crate `Practice` should have a snake case name
  |
  = help: convert the identifier to snake case: `practice`
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.79s
     Running `target\debug\Practice.exe`
days was three
Enter fullscreen mode Exit fullscreen mode

The result does not display error because we have use a bool.

Conclusion
From the above code examples, we have seen how Rust handles control flow. The idiomatic way of writing control flow, as explained earlier, makes the code simple and easy to read. The choice of which construct to use depends on the specific requirements and readability goals of the code. Thank you for reading.

Top comments (0)