Rust Tutorial
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Rust - For Loop



Rust for Loop

The for loop in Rust is used to iterate over a given sequence and executes a set of statements for each element in the sequence. A sequence can be any structure like ranges, and collections like arrays and vectors.

A for loop over a collection can be achieved in two ways. First by using shared borrow operator & and second by using iter() method. Please see the syntax below:

Syntax

//for loop over range
for(variable in range){
  statements;
} 

//for loop over a collection
//using shared borrow operator
for(variable in &collection){
  statements;
} 

//for loop over a collection
//using iter() method
for(variable in collection.iter()){
  statements;
} 

for loop over a Range

In the example below, for loop is used over a given range to print all elements in it.

fn main () {
  //for loop over a range
  for i in 1..=5 {
    println!("i = {}", i); 
  }
}

The output of the above code will be:

i = 1
i = 2
i = 3
i = 4
i = 5

for loop over an Array

In the example below, for loop is used over a given array to print all elements of it.

fn main () {
  //creating an array
  let my_array = [10, 20, 30, 40, 50];

  //for loop over my_array using 
  //shared borrow operator
  for i in &my_array {
    println!("i = {}", i); 
  }
}

The output of the above code will be:

i = 10
i = 20
i = 30
i = 40
i = 50

for loop over a Vector

In the example below, for loop is used over a given vector to print all elements of it.

fn main () {
  //creating a vector
  let my_vector = vec![11, 12, 13, 14, 15];

  //for loop over my_vector
  //using iter() method
  for i in my_vector.iter() {
    println!("i = {}", i); 
  }
}

The output of the above code will be:

i = 11
i = 12
i = 13
i = 14
i = 15

5