In Rust, you can implement iterators for a custom struct efficiently without duplicating code by using the iterator traits strategically. Here's a recommended approach:
struct MyStruct {
data: Vec<i32>,
}
// Base iterator struct that can be cloned and reused
struct MyIterator<'a, T> {
inner: &'a [T],
current: usize,
}
impl<'a, T> Iterator for MyIterator<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.current < self.inner.len() {
let item = &self.inner[self.current];
self.current += 1;
Some(item)
} else {
None
}
}
}
impl MyStruct {
// Immutable iterator
fn iter(&self) -> MyIterator<i32> {
MyIterator {
inner: &self.data,
current: 0,
}
}
// Mutable iterator
fn iter_mut(&mut self) -> MyIterator<&mut i32> {
MyIterator {
inner: &mut self.data,
current: 0,
}
}
// Consuming iterator
fn into_iter(self) -> MyIterator<i32> {
MyIterator {
inner: self.data,
current: 0,
}
}
}
Key benefits of this approach:
- Single iterator implementation
- Supports different iterator types (immutable, mutable, owned)
- Minimal code duplication
- Generic implementation that works with different types
The main techniques here are:
- Using a generic iterator struct
- Implementing the
Iterator trait
- Providing different iterator methods (
iter(), iter_mut(), into_iter())
This pattern allows you to create flexible iterators with minimal code repetition. The generic type T and lifetime 'a provide the flexibility to handle different iterator scenarios.
Would you like me to elaborate on any part of this implementation?