WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Intermediate · question 38 of 100

How do you create a custom iterator in Rust? Provide an example using a simple struct.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, you can create a custom iterator by implementing the ‘Iterator‘ trait. The ‘Iterator‘ trait is the cornerstone of Rust’s iterator system, it defines a single method called ‘next‘, which returns an ‘Option<T>‘.

Here is an example implementation of a custom iterator using a simple struct in Rust:

    struct MyIterator {
        items: Vec<i32>,
        index: usize,
    }
    
    impl MyIterator {
        fn new(items: Vec<i32>) -> MyIterator {
            MyIterator { items: items, index: 0 }
        }
    }
    
    impl Iterator for MyIterator {
        type Item = i32;
        
        fn next(&mut self) -> Option<i32> {
            if self.index < self.items.len() {
                let item = self.items[self.index];
                self.index += 1;
                Some(item)
            } else {
                None
            }
        }
    }

In this example, we create a ‘MyIterator‘ struct that wraps a ‘Vec<i32>‘ and keeps track of the index of the next element to return. The ‘Iterator‘ implementation for ‘MyIterator‘ specifies that the ‘Item‘ type is ‘i32‘, and the ‘next‘ method returns an ‘Option<i32>‘.

To use this custom iterator, we can call the ‘new‘ method to create a new instance of ‘MyIterator‘, and then use it in a ‘for‘ loop like this:

    fn main() {
        let items = vec![1, 2, 3, 4, 5];
        let mut my_iter = MyIterator::new(items);
        
        for item in my_iter {
            println!("{}", item);
        }
    }

This will output the following:

    1
    2
    3
    4
    5

In this example, we create a ‘Vec‘ of integers and pass it to the ‘new‘ method of ‘MyIterator‘. We then use ‘my_iter‘ in a ‘for‘ loop, which calls the ‘next‘ method of ‘MyIterator‘ repeatedly until it returns ‘None‘. Each item returned by ‘next‘ is printed to the console.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics