Quantcast
Viewing latest article 4
Browse Latest Browse All 43

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

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

Image may be NSFW.
Clik here to view.
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"

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

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

Image may be NSFW.
Clik here to view.
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.

fnmain(){letage=13;ifage>=13{println!("Yes, your age is in an acceptable range");}else{println!("Minimum age is 13");}}

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.

fnmain(){letname="John";ifname=="Jane"{println!("Jane logged in");}elseifname=="John"{println!("John logged in");}else{println!("I don't know this person. Call the security");}}

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

fnmain(){letname="Ali";ifname=="Jane"{println!("Jane logged in");}ifname=="John"{println!("John logged in");}ifname!="John"&&name!="Jane"{println!("I don't know this person. Call the security");}}

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?

fnmain(){letis_valid=true;letthe_page=ifis_valid{"admin"}else{"user"};println!("You see the {} page",the_page);}

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.

fnmain(){loop{println!("I'm living here");}}

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.

fnmain(){letmutcounter=0;letresult=loop{counter+=1;ifcounter==1000{breakcounter;}};println!("The result is {}",result);}

while loop

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

fnmain(){letmutcounter=0;whilecounter!=3{counter+=1;println!("Counter is {}",counter);}println!("Loop terminated!");}

for loop

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

fnmain(){letnames=["John","Jane","Ben","Jack","Burak","Ali"];letmutindex=0;whileindex<6{println!("the name is: {}",names[index]);index+=1;}}

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

fnmain(){letnames=["John","Jane","Ben","Jack","Burak","Ali"];fornameinnames.iter(){println!("the name is: {}",name);}}

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;

letnames=["John","Jane","Ben"];whileindex<6{println!("the name is: {}",names[index]);index+=1;}

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

fnmain(){letfirst_number=1;letsecond_number=5;fornumberinfirst_number..second_number{println!("the number is: {}",number);}}

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

Resources


Viewing latest article 4
Browse Latest Browse All 43

Trending Articles