Implement Iterator Trait
Write a Rust function that returns a Vec
Implementing Iterator in Rust requires fulfilling two requirements: defining the associated type Item (what type the iterator yields), and implementing the next() method which returns Option
The Iterator trait is one of Rust's most important traits. Custom iterator implementations enable your types to work seamlessly with the entire iterator ecosystem: for loops, .map(), .filter(), .collect(), and hundreds of other adapter methods provided by the standard library. The trait's associated type mechanism ensures type safety across the chain.
Time complexity is O(n) for collecting n elements, with O(1) per next() call. Space complexity is O(1) for the iterator state, O(n) for the collected Vec. The iterator is lazy — no elements are computed until next() is called or the iterator is consumed.
Edge cases include max = 0 (the iterator immediately returns None on first next() call), large values of max, and ensuring the struct correctly tracks its internal state across multiple next() calls without external mutation.
Example Input & Output
Step iterator yields 0..5
Zero steps, empty
Single step
Three steps
Two steps
Algorithm Flow

Solution Approach
Best Answers
struct Step {
current: i32,
max: i32,
}
impl Iterator for Step {
type Item = i32;
fn next(&mut self) -> Option<i32> {
if self.current < self.max {
let val = self.current;
self.current += 1;
Some(val)
} else {
None
}
}
}
fn solution(max: i32) -> Vec<i32> {
let step = Step { current: 0, max };
step.collect()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
