Iterator trait — implement next() and other methods.
Basic implementation:
1struct Counter {2 count: u32,3 max: u32,4}56impl Iterator for Counter {7 type Item = u32;89 fn next(&mut self) -> Option<Self::Item> {10 if self.count < self.max {11 self.count += 1;12 Some(self.count)13 } else {14 None15 }16 }17}1819let counter = Counter { count: 0, max: 5 };20for i in counter {21 println!("{}", i); // 1, 2, 3, 4, 522}
Using iterator adapters:
1let sum: u32 = (1..=10)2 .filter(|x| x % 2 == 0)3 .map(|x| x * x)4 .sum();
Key: Implement Iterator trait for custom iteration.