loop through vector in rust

In Rust, we can loop through a vector using a for loop. Here's the syntax:

main.rs
let vector = vec![1, 2, 3, 4, 5];
for element in vector {
    println!("{}", element);
}
89 chars
5 lines

In the code above, we first create a vector containing the integers 1 to 5. We then use a for loop to iterate over each element in the vector, printing each element to the console.

Alternatively, we can use a for loop with a range to access the elements of the vector by index:

main.rs
let vector = vec![1, 2, 3, 4, 5];
for i in 0..vector.len() {
    println!("{}", vector[i]);
}
94 chars
5 lines

Here, we use a for loop with a range that goes from 0 to vector.len() - 1, accessing each element of the vector using its index.

gistlibby LogSnag