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

It reduces the lines of code and code cleaner.

Rust for loop

Here is an syntax

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

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

variable is an temporary variable assigned with each iterated values.

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

Here is the sequence of steps

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

Here is an example

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

    for 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 loop 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 item in 1..=5 {
        println!("{}",item);
    }
}

Output:

1
2
3
4
5

Rust for loop with index example

This examples explains how to iterate the values in a vector and prints the value and index.

iter() trait return 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