DEV Community

Cover image for Control Flow Statements in Rust
Itachi Uchiha
Itachi Uchiha

Posted on

Control Flow Statements in Rust

This post published on my blog before


Hi everyone. Before that, I wrote a post called Playing with Functions in Rust.

Today I'll try to explain control flow statements in Rust

Before starting, I’ll create a project with cargo;

cargo new control_flow

cd control_flow
Enter fullscreen mode Exit fullscreen mode

Introduction

Rust has control statements like if expressions and loops. Mostly you'll see if expressions and loops in Rust. If you're new in programming, don't worry about if expressions and loops. Because you already familiar with these control statements.

If Expressions in Real Life

Decision Making
Image from Comomag

When you decided to buy a new television, you will check your budget firstly. If you have enough money, you will pay for it. If you don't have enough money, you could have several possible scenarios. Let's write a basic scenario our first if expression.

1-) I go to the technology store
2-) I look for a television
3-) I saw a television
4-) I call someone to buy it
5-) I asked for price for it
6-) The employee told me "$4.000"
Enter fullscreen mode Exit fullscreen mode

Until this step, we didn't have to make a decision.

7-) Hmm, do I have enough money? --> our first query
  7.1-) If I have enough money
    Tell the employee: I'll buy it.
  7.2-) I don't have enough money 
    Ask the employee: Do you have installment options for this product?
    7.2.1-) If there are installment options
      Tell the employee, I'll buy it
    7.2.2-) If there is no installment
      Look for a new television or left the store
Enter fullscreen mode Exit fullscreen mode

Actually, step 7.2.1 can be extending. For example, you could ask about installment options. If you don't like the options, probably you don't want to buy it. But, we know that we're always making decisions in real life. Because this is who we are.

Loops in Real Life

Daily Routine
Image from Freepik

If we explain a loop, we can say that a job we do regularly.

Do you go to work every day?
Do you go to school every day?
Do you visit your parents every weekend?

These are loops in your life.

The sun rises every morning. This is the most important loop in the world.

I hope you understand if expressions and loops in this way. Let's back to the programming.

if Expressions

We know how an if expression works. An if expression allows you to make decisions. In programming languages when you control something, the result should be true or false. Some programming languages like JavaScript, Python accepts truthy or falsy values. Let's write our first if expression in Rust.

fn main() {
  let age = 13;
  if age >= 13 {
    println!("Yes, your age is in an acceptable range");
  } else {
    println!("Minimum age is 13");
  }
}
Enter fullscreen mode Exit fullscreen mode

As you see an if expression starts with the if keyword. But what is this else keyword. You checked for something but the condition didn't return true but we want to say something about this condition, we use else keyword.

Multiple Conditions with else if Keyword

If you're checking a name, you could have several possible values. This name can be John or Jane or non of them.

fn main() {
  let name = "John";

  if name == "Jane" {
    println!("Jane logged in");
  } else if name == "John" {
    println!("John logged in");
  } else {
    println!("I don't know this person. Call the security");
  }
}
Enter fullscreen mode Exit fullscreen mode

It will return John logged in. So, else if keyword is a way to combine if expressions. You can write these expressions like that;

fn main() {
  let name = "Ali";

  if name == "Jane" {
    println!("Jane logged in");
  } 

  if name == "John" {
    println!("John logged in");
  } 

  if name != "John" && name != "Jane" {
    println!("I don't know this person. Call the security");
  }
}
Enter fullscreen mode Exit fullscreen mode

But this doesn't look a good way.

if with let keyword

If you didn't hear about ternary if before, you'll know what is it now. A ternary if, basically single line if. So, how it works in Rust?

fn main() {
  let is_valid = true;
  let the_page = if is_valid { "admin" } else { "user" };

  println!("You see the {} page", the_page);
}
Enter fullscreen mode Exit fullscreen mode

But don't forget this, the second condition's value must be the same with first condition's value.

Loops in Rust

A loop executes a code block more than once or only one. This depends on your code. Rust has three types of loops: loop, while and for. You may have heard the while andfor loops before.

loop keyword

The loop keyword tells Rust to execute a block of code over and over again forever or until you explicitly tell it to stop.

fn main() {
  loop {
    println!("I'm living here");
  }
}
Enter fullscreen mode Exit fullscreen mode

When we run this program, we’ll see I'm living here printed over and over continuously until we stop the program manually.

Returning Values from Loops

I don't know is there something like that in the other programming languages, but you can return values from a loop in Rust. For example, you have a counter and it should return a value when it stopped by break keyword.

fn main() {
  let mut counter = 0;
  let result = loop {
    counter += 1;

    if counter == 1000 {
      break counter;
    }
  };

  println!("The result is {}", result);
}
Enter fullscreen mode Exit fullscreen mode

while loop

This loop works when condition is true. For example, you check for counter != 3;

fn main() {
  let mut counter = 0;

  while counter != 3 {
      counter += 1;

      println!("Counter is {}", counter);
  }

  println!("Loop terminated!");
}
Enter fullscreen mode Exit fullscreen mode

for loop

You can iterate collections with while loop and for loop. If you're choosing while loop it would be like that;

fn main() {
    let names = ["John", "Jane", "Ben", "Jack", "Burak", "Ali"];
    let mut index = 0;

    while index < 6 {
        println!("the name is: {}", names[index]);

        index += 1;
    }
}
Enter fullscreen mode Exit fullscreen mode

You can iterate collections such as arrays with for loop in Rust;

fn main() {
    let names = ["John", "Jane", "Ben", "Jack", "Burak", "Ali"];

    for name in names.iter() {
        println!("the name is: {}", name);
    }
}
Enter fullscreen mode Exit fullscreen mode

Actually, this is much safer than the while loop. Because you maybe don't have a chance to know the size of the array. Let's assume you have an array like that;

let names = ["John", "Jane", "Ben"];

while index < 6 {
  println!("the name is: {}", names[index]);

  index += 1;
}
Enter fullscreen mode Exit fullscreen mode

Will it work? No! Your code will panic. You can also loop in range with for loop. Let me show you.

fn main() {
    let first_number = 1;
    let second_number = 5;

    for number in first_number..second_number {
        println!("the number is: {}", number);
    }
}
Enter fullscreen mode Exit fullscreen mode

That’s all for now. If there is something wrong, please let me know. Thanks for reading.

Resources

Top comments (0)