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.