Iterators in Rust
In this lesson, you will learn about iterators in Rust. Iterators provide a powerful, safe, and efficient way to process collections such as vectors, arrays, and ranges.
Rust’s iterator system is one of its strongest features and is heavily used throughout the standard library.
What Is an Iterator?
An iterator is an object that allows you to traverse a sequence of values one at a time.
In Rust, iterators follow a common interface defined by the Iterator trait.
The Iterator Trait
The core of Rust’s iteration system is the Iterator trait.
It defines a single required method called next().
trait Iterator {
type Item;
fn next(&mut self) -> Option;
}
The next() method returns:
Some(value)when a value is availableNonewhen iteration is finished
Creating an Iterator
Most collections provide an iterator using the iter() method.
let numbers = vec![1, 2, 3, 4];
let mut iter = numbers.iter();
Using next() Manually
You can manually step through an iterator using next().
println!("{:?}", iter.next());
println!("{:?}", iter.next());
println!("{:?}", iter.next());
Iterating with a for Loop
The most common way to use iterators is with a for loop.
for value in numbers.iter() {
println!("{}", value);
}
Rust automatically calls next() behind the scenes.
Iterator Methods
Rust provides many built-in methods for iterators. These methods return new iterators instead of modifying the original.
map()
The map() method transforms each element.
let doubled: Vec = numbers.iter().map(|x| x * 2).collect();
println!("{:?}", doubled);
filter()
The filter() method keeps elements that match a condition.
let even: Vec = numbers.iter()
.filter(|x| *x % 2 == 0)
.collect();
println!("{:?}", even);
collect()
The collect() method converts an iterator into a collection.
let values: Vec = (1..5).collect();
println!("{:?}", values);
Ownership and Iterators
Rust provides three main ways to iterate over a collection:
iter()— borrows elementsiter_mut()— borrows elements mutablyinto_iter()— takes ownership of elements
for x in numbers.iter() {
println!("{}", x);
}
Lazy Evaluation
Iterators in Rust are lazy. This means they do nothing until they are consumed.
Methods like map() and filter() only run when
collect() or a loop is used.
Chaining Iterator Methods
You can chain multiple iterator methods together.
let result: Vec = numbers.iter()
.map(|x| x * 2)
.filter(|x| *x > 4)
.collect();
println!("{:?}", result);
Why Iterators Are Important
Iterators provide:
- Clear and readable code
- High performance
- Memory safety
- Zero-cost abstractions
📝 Practice Exercises
Exercise 1
Create an iterator from a vector and print each value.
Exercise 2
Use map() to double each value in a vector.
Exercise 3
Filter out odd numbers from a list.
Exercise 4
Chain map() and filter() together.
✅ Practice Answers
Answer 1
let nums = vec![1, 2, 3];
for n in nums.iter() {
println!("{}", n);
}
Answer 2
let doubled: Vec = nums.iter().map(|x| x * 2).collect();
Answer 3
let even: Vec = nums.iter().filter(|x| *x % 2 == 0).collect();
Answer 4
let result: Vec = nums.iter()
.map(|x| x * 2)
.filter(|x| *x > 3)
.collect();
What’s Next?
In the next lesson, you will learn about Closures in Rust — functions that capture their environment and work seamlessly with iterators.