Rust for Loop
In Rust, you can use the for
loop to iterate over collections of items, such as arrays, vectors, and ranges. The basic syntax for a for
loop is as follows:
for item in collection { // code to execute for each item }
Here's an example of iterating over a range of numbers:
for num in 0..10 { println!("Number is {}", num); }
In this example, we're iterating over a range of numbers from 0 to 9 (inclusive). Inside the loop, we're printing the current value of num
using the println!
macro.
You can also use a for
loop with arrays or vectors. Here's an example using a vector:
let numbers = vec![1, 2, 3, 4, 5]; for num in numbers { println!("Number is {}", num); }
In this example, we're iterating over a vector of numbers. The loop will execute once for each item in the vector, and the num
variable will be set to the current item. We're then printing the value of num
using the println!
macro.
Note that when using a for
loop with a collection, the loop will automatically iterate over each item in the collection, so you don't need to manually keep track of an index variable like you might in other languages.