For example, you want to print a hello message 10 times. Usually use print statements 10 times. To run the same task multiple times, For loop is introduced in Rust.

It reduces the lines of code and code cleaner.

Rust for loop

Here is a syntax

for variable in expression-iterator{
    //code statements
}

expression-iterator: is a Rust expression that valid iterator, Iterates each element in an expression, and the element is mapped to the variable, It can be vector or iterated types.

variable is a temporary variable assigned with each iterated value.

for and in are keywords in rust used to construct for loop in rust

Here is the sequence of steps

  • Iterates each element from an expression
  • assigned to a variable
  • executes code statements
  • Select the next iterated value and repeat the above steps until all elements are iterated in the expression

Here is an example

fn main() {
    let array = [1, 2,3, 4, 5];

    for an item in array {
        println!("{}",item);
    }
}

Output:

1
2
3
4
5

for in loop has three variations to convert collections into iterators.

  • iter :

  • Iterates the

  • into_iter

  • iter_mut Let’s see some examples of for loops in Rust

Rust for loop with range

This example iterates the range of values and prints it.

Range of values created using notation start..=end.

for example 1..5 range iterator iterates from 1 to 5.

1..5 is with values 1,2,3,4 values 1..=5 is with values 1,2,3,4,5 values

fn main() {
    for an item in 1..=5 {
        println!("{}",item);
    }
}

Output:

1
2
3
4
5

Rust for loop with index example

This example explains how to iterate the values in a vector and print the value and index.

iter() trait returns the iterated values of collections

fn main() {
    let numbers: &[i64] = &vec![1, 2, 3, 4, 5];

    for (i, item) in numbers.iter().enumerate() {
        println!("value: - {} - Index: {}", item,i);
    }
}

Output:

value: - 1 - Index: 0
value: - 2 - Index: 1
value: - 3 - Index: 2
value: - 4 - Index: 3
value: - 5 - Index: 4