Rust Programming: Iterate over the Values in a Vector

0

Iterating over the values in a vector in Rust is a common way to process all of the elements in the vector one at a time. There are two main ways to iterate over a vector: using a for loop and using an iterator.

Using a for loop

To iterate over a vector using a for loop, we can use the in keyword to iterate over the elements of the vector, one at a time. For example, the following code will print all of the elements in the vector v to the console:

Rust
let v = vec![1, 2, 3, 4, 5];

for i in v {
    println!("{i}");
}

Using an iterator

Iterators are a more powerful way to iterate over vectors in Rust. Iterators allow us to perform more complex operations on the elements of the vector, such as filtering, mapping, and reducing.

To use an iterator to iterate over a vector, we first need to call the iter() method on the vector. This will return an iterator that can be used to iterate over the elements of the vector.

Once we have an iterator, we can use it in a variety of ways. For example, the following code will print all of the even numbers in the vector v to the console:

Rust
let v = vec![1, 2, 3, 4, 5];

for i in v.iter().filter(|x| x % 2 == 0) {
    println!("{i}");
}

Iterating over mutable vectors

We can also iterate over mutable vectors in Rust. To do this, we need to call the iter_mut() method on the vector instead of the iter() method. This will return an iterator that can be used to iterate over the mutable elements of the vector.

Once we have a mutable iterator, we can use it to modify the elements of the vector. For example, the following code will double the value of each element in the vector v:

Rust
let mut v = vec![1, 2, 3, 4, 5];

for i in v.iter_mut() {
    *i *= 2;
}

Borrow checker safety

Iterating over a vector, whether immutably or mutably, is safe because of the borrow checker's rules. The borrow checker prevents us from modifying the vector while we are iterating over it.

For example, the following code will not compile:

Rust
let mut v = vec![1, 2, 3, 4, 5];

for i in v.iter_mut() {
    v.push(6);
}

The compiler will give us an error because we are trying to modify the vector while we are iterating over it.

Post a Comment

0Comments
Post a Comment (0)