In Rust, you can create a custom iterator by implementing the ‘Iterator‘ trait. The ‘Iterator‘ trait is the cornerstone of Rust’s iterator system, it defines a single method called ‘next‘, which returns an ‘Option<T>‘.
Here is an example implementation of a custom iterator using a simple struct in Rust:
struct MyIterator {
items: Vec<i32>,
index: usize,
}
impl MyIterator {
fn new(items: Vec<i32>) -> MyIterator {
MyIterator { items: items, index: 0 }
}
}
impl Iterator for MyIterator {
type Item = i32;
fn next(&mut self) -> Option<i32> {
if self.index < self.items.len() {
let item = self.items[self.index];
self.index += 1;
Some(item)
} else {
None
}
}
}
In this example, we create a ‘MyIterator‘ struct that wraps a ‘Vec<i32>‘ and keeps track of the index of the next element to return. The ‘Iterator‘ implementation for ‘MyIterator‘ specifies that the ‘Item‘ type is ‘i32‘, and the ‘next‘ method returns an ‘Option<i32>‘.
To use this custom iterator, we can call the ‘new‘ method to create a new instance of ‘MyIterator‘, and then use it in a ‘for‘ loop like this:
fn main() {
let items = vec![1, 2, 3, 4, 5];
let mut my_iter = MyIterator::new(items);
for item in my_iter {
println!("{}", item);
}
}
This will output the following:
1
2
3
4
5
In this example, we create a ‘Vec‘ of integers and pass it to the ‘new‘ method of ‘MyIterator‘. We then use ‘my_iter‘ in a ‘for‘ loop, which calls the ‘next‘ method of ‘MyIterator‘ repeatedly until it returns ‘None‘. Each item returned by ‘next‘ is printed to the console.