Rust For Loop
For loop
The for loop executes for the specified number of times; it is a conditional loop. Rust behaves slightly differently from other languages when using a for loop. Until the condition is true, the for loop is run.
Syntax of for loop
for var in expression
{
//block statements
}
An expression can be transformed into an iterator that iterates across a data structure’s elements using the syntax shown above. Value is retrieved from an iterator at each iteration. The loop ends when there are no more values to be fetched.
Example
fn main()
{
for i in 1..11
{
print!("{} ",i);
}
}
Output:
1 2 3 4 5 6 7 8 9 10
1..11 is an expression in the example above, and the iterator will loop over these numbers. Because the upper bound is exclusive, the loop will print numbers between 1 and 10.
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
The table of two is printed by the for loop in the example above.
Example
fn main()
let fruits=["mango","apple","banana","litchi","watermelon"];
for a in fruits.iter()
{
print!("{} ",a);
}
Output:
mango apple banana litchi watermelon
The iter() technique is used in the example above to retrieve each element of the fruits variable. The loop ends when it reaches the final element of an array.
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.