Rust for loop
Created By: chatGPT
Rust provides a powerful and flexible way to iterate over collections using the
In this example, we define an array of integers called for
loop. This is particularly useful when you need to perform actions on each element of an array or a vector. The for
loop in Rust can also be used with ranges, making it easier to iterate a certain number of times. Below is a basic example of a for
loop that iterates over an array.fn main() {
let numbers = [1, 2, 3, 4, 5];
for &number in &numbers {
println!("Number: {}", number);
}
}
numbers
. The for
loop iterates through each element of the array. Notice the use of &numbers
to create a reference to the array, and &number
to destructure the reference in each iteration. This prevents ownership issues and allows us to access the value directly as number
. Each number is printed to the console.You can also use a range to iterate a specific number of times. Here's how you can do that using the
In this case, the for
loop with a range from 1 to 5.fn main() {
for i in 1..=5 {
println!("Iteration: {}", i);
}
}
1..=5
range includes both endpoints, allowing the loop to run from 1 through 5. The ..=
operator indicates that the range is inclusive. This is particularly useful when you have a fixed number of iterations.Combining
In summary, the for
loops with collections is a common pattern in Rust. Here’s how you can use for
loops with a vector, which is a growable array type in Rust.fn main() {
let mut vec_numbers = vec![10, 20, 30, 40, 50];
for number in &vec_numbers {
println!("Vector Number: {}", number);
}
}
for
loop in Rust is versatile and can be adapted to various data types such as arrays, vectors, and ranges. Utilizing its capabilities can help you write clean and efficient code while performing iterative tasks.