Iterating Over a Vector
Iterating Over a Vector
If it is desired to access each element of a vector, then it is possible to iterate over the elements of a vector using iter()
rather than using the indexes
to access a particular element of a vector using the square bracket notation
Iterate Using .iter()
Built-in Method
we learned to remove an element given an index. However, to remove a particular element, we first need to find the index of that element and then call the remove function passing that index.
For this we can use the
.iter().position(|&e| e == element_name).unwrap()
.
Here,
iter()
is the built-in function that iterates over the elements of the vector..position
is a built-in function that takes the element name to get the position of that element in the vector, i.e.,(|&e| e == element_name)
defines a variable e with the value equal to the name of the element that we want to find..unwrap()
is the built-in function.
output
As you can see the value 2 is removed from the vector. you’ll learn how the iterator function helps to loop through each element in the vector index-by-index.
Loop Through the Values
- Define a vector variable.
- The values of the vector within the loop can be traversed using
.iter()
.
📝If you don’t write .iter()
within the loop defination, a simple for loop will give you the same result.
output
Loops and Mutate Values
- Define a mutable vector variable
- The values of the vector within the loop can be changed using
.iter_mut()
.
The following illustration shows how the above code works:
Quiz
Test your understanding of looping through a vector in Rust.
Last updated a year ago.