Rust 101: Loops
In the previous article, we discussed about Collections in rust. Now let’s dive into Loops.
TL;DR
- For loop
- Infinite For loop
- While loop
First, let’s start off by creating a new project called “Loops” using the following command
cargo new Loops --bin
For loop
For loop just like any other language runs a block of code a fixed number of times
Here is the syntax
for <iterating var> in <start index>..<end index>{ //code block}
Enumerate
Enumerate is a type of for loop which allows for two variables iteration. Enumerate is similar to the zip command in python.
Here is the syntax
for <iterating var> in (<start index>..<end index>).enumerate(){ //code block}
The output for the above program is
0,1
1,2
2,3
3,4
4,5
5,6
6,7
7,8
8,9
We can use this to iterate through collections. In this case the program outputs the index followed by the elements in a given array
The output for the above program is
0,1
1,2
2,3
3,4
Infinite For loop
Rust offers infinite loops rite out of the box.
Here is the syntax
loop{ //code block}
While Loop
While loop just like any other language runs a block of code a fixed number of times based on a condition
Here is the syntax
while <condition>{ //Code block}
Note:
Rust has no do-while loops
In the next article, we will discuss about Conditional statements.
link to the next article
Link to the previous article