How do you implement a custom iterator in Rust?
Assesses fundamental understanding of Rust conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
You implement the Iterator trait by providing next, which returns Option<Self::Item>.
struct Counter { count: u32, max: u32 }
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.count < self.max {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
let sum: u32 = Counter { count: 0, max: 5 }.sum();
The trait provides dozens of adapters such as map, filter, take, zip and fold. They are lazy: nothing runs until a consuming method like collect, sum or a for loop drives the iterator. This laziness plus monomorphisation produces efficient pipelines that often compile to the same code as a hand-written loop.
Implement size_hint when the length is known to help collect preallocate, and implement ExactSizeIterator or DoubleEndedIterator when the guarantees hold. Iterators are the idiomatic way to process sequences in Rust.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.