Rust iterator
Created By: chatGPT
In Rust, an iterator is an abstraction that enables you to work with sequences of items. The Iterator trait is the foundation of iterators in Rust and provides a way to produce a sequence of values, one at a time, while maintaining state between calls. This allows for various operations such as mapping, filtering, and reducing collections of data in an efficient way.
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
To create a custom iterator, you typically implement the Iterator trait for your struct. Below is an example of a simple iterator that yields numbers from a given start to an endpoint.
struct Counter {
count: usize,
max: usize,
}
impl Counter {
fn new(max: usize) -> Counter {
Counter { count: 0, max }
}
}
impl Iterator for Counter {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.count < self.max {
self.count += 1;
Some(self.count - 1)
} else {
None
}
}
}
You can use this
Counter
iterator as follows:fn main() {
let mut counter = Counter::new(5);
while let Some(value) = counter.next() {
println!("Counter: {}", value);
}
}
Rust's built-in iteration methods can transform and manipulate your collections using iterators. Some common methods include map, filter, and fold. Here’s an example of using these methods with a vector of integers.
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
// Map: square each number
let squares: Vec<_> = numbers.iter().map(|&x| x * x).collect();
// Filter: keep only even numbers
let evens: Vec<_> = numbers.iter().filter(|&&x| x % 2 == 0).collect();
// Fold: sum all numbers
let sum: i32 = numbers.iter().fold(0, |acc, &x| acc + x);
println!("Squares: {:?}", squares);
println!("Evens: {:?}", evens);
println!("Sum: {}", sum);
}