Code Logo

Implement Iterator Trait

Published at25 Jul 2026
Rust Collections Hard 0 views
Like0

Write a Rust function that returns a Vec by implementing the Iterator trait on a custom struct called Step. The Step struct holds a current value and a max value. Implementing Iterator requires defining the Item type and the next() method. Each call to next() returns the current value and increments it, stopping when current reaches max.

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 next() method returns Some(value) if there are more elements, or None when iteration is complete. This is the fundamental trait that enables for loops and iterator adapters.

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

Example 1
Input
5
Output
[0,1,2,3,4]
Explanation

Step iterator yields 0..5

Example 2
Input
0
Output
[]
Explanation

Zero steps, empty

Example 3
Input
1
Output
[0]
Explanation

Single step

Example 4
Input
3
Output
[0,1,2]
Explanation

Three steps

Example 5
Input
2
Output
[0,1]
Explanation

Two steps

Algorithm Flow

Recommendation Algorithm Flow for Implement Iterator Trait
Recommendation Algorithm Flow for Implement Iterator Trait

Solution Approach

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()
}

Best Answers

rust - Approach 1
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()
}