How to iterate over an array in Rust?

In Rust, there are several ways to iterate over an array. Here are a few examples:

Using a for loop

One of the simplest and most common ways to iterate over an array in Rust is to use a for loop. Here's an example:


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

    for item in my_array.iter() {
        println!("{}", item);
    }
}					

In this example, we define an array my_array containing five integers. We then use a for loop to iterate over each item in the array using the iter() method, which returns an iterator over the array. Inside the loop, we simply print each item to the console.

Using a while loop with an index

Another way to iterate over an array in Rust is to use a while loop with an index. Here's an example:

								
									fn main() {
    let my_array = [1, 2, 3, 4, 5];
    let mut index = 0;

    while index < my_array.len() {
        println!("{}", my_array[index]);
        index += 1;
    }
}								
							

In this example, we define an array my_array containing five integers. We then use a while loop to iterate over the array using an index variable index, which starts at 0. Inside the loop, we print the item at the current index to the console using square brackets, and then we increment the index variable.

Using a for loop with enumerate()

A third way to iterate over an array in Rust is to use a for loop with the enumerate() method. Here's an example:

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

for (index, item) in my_array.iter().enumerate() {
    println!("{}: {}", index, item);
}								
							

In this example, we define an array my_array containing five integers. We then use a for loop with the enumerate() method to iterate over the array and get both the index and the item at each position. Inside the loop, we print both the index and the item to the console using curly braces.

Suggested Further Reading

How to reverse a string in Rust?

In this example, you will learn how to reverse a string and how to reverse each word of a sentence.

Read more 

How do you iterate a vector in Rust?

There are several ways to iterate a vector in Rust. Here are four different ways:

Read more 

How do I split a string in Rust?

In Rust, you can split a string into substrings using the split method, which returns an iterator over the substrings. You can split the string based on a delimiter, such as a space or a comma.

Read more 

Rust remove first character from string

In Rust, there are several ways to remove the first character from a string. Here are a few examples:

Read more 

Examples of string match in Rust

You will learn to identify and pick a suitable solution to match a string.

Read more