rust iterate over vector

To iterate over the elements of a vector in Rust, you can use a for loop. Here’s an example:

The for loop is a convenient way to iterate over the elements of a vector. It allows you to write a loop that will execute a block of code for each element in the vector.
for variable in iterable {
    code to execute
}

In the case of a vector, the iterable is the vector itself, and variable is a variable that will be assigned to each element of the vector in turn.

rust iterate over vector

Here’s an example of a for loop that iterates over a vector of integers:

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

    for number in numbers {
        println!("{}", number);
    }
}

This will print the numbers 1 through 5 on separate lines.

You can also use the iter() method on a vector to get an iterator over its elements, and then call next() on the iterator to retrieve the elements one by one. Here’s an example:

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

    let mut iterator = numbers.iter();

    while let Some(number) = iterator.next() {
        println!("{}", number);
    }
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *