Optimum Web
Software Development 6 min read

Iterators in Rust: What Are They and How to Iterate Over a Vector

VP

Vasili Pascal

Co-Founder & Developer

Iterators in Rust are the objects that implement the Iterator trait and can be used to iterate over a collection of values.

The Iterator trait defines several methods, including .next(), which returns the next value in the iteration, and size_hint(), which hints at the number of remaining elements.

Here's an example of using an iterator to iterate over the elements of a vector:

``rust let mut v = vec![1, 2, 3]; for i in v.iter() { println!("{}", i); }``

This will print the elements of the vector, one per line.

Iterators are a fundamental concept in Rust and are used in many places, including for-loops, Iterator::collect(), and the Iterator::map() method. They can be created manually or by using functions or methods that return iterators, such as .iter() on a collection.

Methods to Iterate Over a Vector in Rust

In Rust, iteration refers to repeatedly executing a block of code for each element in a collection. Depending on your specific needs, there are several ways to iterate over a vector in Rust.

**1. Using a for loop:**

``rust let mut vec = vec![1, 2, 3]; for element in vec { println!("{}", element); }``

**2. Using `iter()` and `.next()`:**

``rust let vec = vec![1, 2, 3]; let mut iterator = vec.iter(); while let Some(element) = iterator.next() { println!("{}", element); }``

**3. Using `iter_mut()` and `.next()` (mutable iteration):**

``rust let mut vec = vec![1, 2, 3]; let mut iterator = vec.iter_mut(); while let Some(element) = iterator.next() { *element *= 2; }``

**4. Using `enumerate()` and a for loop:**

``rust let vec = vec![1, 2, 3]; for (index, element) in vec.enumerate() { println!("Element {} is {}", index, element); }``

It's also possible to use the Iterator trait and .map() to perform an operation on each element and collect the results into a new vector:

``rust let vec = vec![1, 2, 3]; let doubled: Vec<i32> = vec.into_iter().map(|x| x * 2).collect(); println!("{:?}", doubled); // [2, 4, 6]``

Choose the approach that best suits your specific needs. Consult the Rust standard library documentation for the full Iterator trait API.

RustIteratorsProgrammingSystems ProgrammingVectorCollections

Frequently Asked Questions

What is an iterator in Rust?
An iterator in Rust is any type that implements the Iterator trait, which requires a `next()` method returning `Option<Self::Item>`. Iterators are lazy — they don't compute values until consumed — and are used throughout Rust in for-loops, map(), filter(), collect(), and many other contexts.
What is the difference between iter(), iter_mut(), and into_iter()?
`iter()` yields immutable references (`&T`) to each element, leaving the vector intact. `iter_mut()` yields mutable references (`&mut T`), allowing you to modify elements in place. `into_iter()` consumes the vector and yields owned values (`T`). Choose based on whether you need to borrow, mutate, or take ownership.
How do I transform a vector using iterators in Rust?
Use the `.map()` method chained with `.collect()`. For example: `let doubled: Vec<i32> = vec.into_iter().map(|x| x * 2).collect();`. This applies the closure to each element and collects the results into a new vector. You can also chain `.filter()` to keep only elements matching a predicate.
When should I use a for loop vs. iterator adapter methods in Rust?
For-loops are idiomatic for simple iteration where you just need to process each element. Iterator adapters (map, filter, fold, etc.) are preferred when transforming or reducing collections, as they compose naturally and are often more expressive. Both compile to equivalent machine code due to Rust's zero-cost abstractions.