Industrial Training




Rust For Loop

The for loop is a conditional loop, i.e., the loop runs for the particular number of times. The behavior of for loop in rust language is slightly different from the other languages. The for loop is executed till the condition is true.


Syntax of for loop


for var in expression  
{  
    //block statements  
}   

In the above syntax, an expression can be converted into an iterator which iterates through the elements of a data structure. In every iteration, value is fetched from an iterator. When there are no values left to be fetched, loop is over.


Let?s see a simple example.
fn main()  
{  
    
  for i in 1..11  
  {  
    print!("{} ",i);  
  }   
}  

Output:
1 2 3 4 5 6 7 8 9 10

In the above example, 1..11 is an expression and the iterator will iterate over these values. The upper bound is exclusive, so loop will print from 1 to 10 values.


Let?s see a simple example.
fn main()  
{  
let mut result;  
for i in 1..11  
{  
result=2*i;  
println!("2*{}={}",i,result);  
}  
}  

Output:
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
2*10=20

In the above example, for loop prints the table of 2.


Let?s see another simple example.
fn main()  
  
   
 let fruits=["mango","apple","banana","litchi","watermelon"];  
  for a in fruits.iter()  
 {  
   print!("{} ",a);  
 }   

Output:
mango apple banana litchi watermelon 

In the above example, iter() method is used to access the each element of fruits variable. Once, it reaches the last element of an array, then the loop is over.


Difference between the while loop and for loop:


If the index length of an array is increased at runtime, then the while loop shows the bug but this would not be happened in the case of for loop. Therefore, we can say that for loop increases the safety of the code and removes the chances of the bugs.




Hi I am Pluto.