How Many Ways to Apply For loop in Rust?

How Many Ways to Apply For loop in Rust?

Table of contents

No heading

No headings in the article.

In Rust, the for the loop is used to iterate through a collection of items, such as an array or a vector. The basic syntax for a for the loop is as follows:

for variable in collection {
    // code to execute
}

Here variable is a variable that will take on the value of each item in the collection, and collection is an expression that evaluates to the collection you want to iterate over.

For example, let's consider an array of integers and iterate through it using a for loop

let numbers = [1, 2, 3, 4, 5];

for number in numbers {
    println!("The number is: {}", number);
}

You can also use the for loop to iterate through a range of numbers, using the range function. For example:

for i in 0..10 {
    println!("The value of i is: {}", i);
}
//This will print the values from 0 to 9.

You can also use the .iter() method to iterate over an array and use .next() method to get the next item in the iteration.

let numbers = [1, 2, 3, 4, 5];

let mut iterator = numbers.iter();

loop {
    match iterator.next() {
        Some(number) => println!("The number is: {}", number),
        None => break,
    }
}

You can use for loop with different types of collections like arrays, vectors, strings, etc., and use it in different ways as per your requirement.


In Rust, you can use the step_by() method to iterate through a range of numbers with a specific step. The step_by() method takes a single argument, which is the number of steps to take between each iteration.

Here is an example of using a for loop with a range of numbers, but jumping by 2 each time:

for i in (0..10).step_by(2) {
    println!("The value of i is: {}", i);
}

This will print the values 0, 2, 4, 6, and 8.

You can also use this method in a for the loop that iterates through an array or vector.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for i in (0..numbers.len()).step_by(2) {
    println!("The value at index {} is: {}", i, numbers[i]);
}

This will print the values at every 2nd index of the array