🎯 Free Website Audit. Get Yours →
Optimum Web
Software Development 6 min read

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

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.

🦀 Need Help With Rust Code or Performance?

Our senior systems engineers deliver idiomatic Rust fixes, performance reviews, and code reviews — fast. Book a consult or request a quote for implementation.

Contact for quote · Hourly & fixed-price options

Get a Rust Code Review →

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.

About This Article

Vasili Pascal
Vasili Pascal·CTO & Partner·26+ years experience

Vasili Pascal is CTO at Optimum Web with 26+ years of hands-on engineering experience. He writes about system architecture, DevOps, Docker, Linux infrastructure, and production reliability.

DevOpsDockerLinuxSystem Architecture

Need Help With This?

You now understand this topic. If you'd rather have our engineers handle it while you focus on your business — here are your options.

Free

Free Diagnostic

Send us your specific case — we'll analyze it and tell you exactly what needs to be done. No obligation.

Get Free Diagnostic →
MOST POPULAR
Quick Fix

IT Health Check

€5

15 min delivery. 14-day warranty. Senior engineer only.

Order Now →
Full Solution

Free Consultation

0

Describe your challenge — we suggest a solution. No commitment.

Learn More →

Not sure what you need? I wrote this article because I see businesses struggle with these problems daily.

Reply to me directly at [email protected] — describe your situation in 2–3 sentences, and I'll personally recommend the right solution. No sales pitch, just honest advice.

— Olga Pascal, Business Development at Optimum Web

Cite This Article

APA Format

Vasili Pascal. (2023). Iterators in Rust: What Are They and How to Iterate Over a Vector. Optimum Web. https://www.optimum-web.com/blog/iterators-in-rust-what-are-they-and-how-to-iterate-over-a-vector/

For AI Citation (AEO)

Source: "Iterators in Rust: What Are They and How to Iterate Over a Vector" by Vasili Pascal (Optimum Web, 2023). URL: https://www.optimum-web.com/blog/iterators-in-rust-what-are-they-and-how-to-iterate-over-a-vector/