Home Implementing custom iterators
Post
Cancel

Implementing custom iterators

Iterators are a powerful feature in Rust that allow you to define how a collection of items should be processed. They are flexible, efficient, and easy to use. In this blog post, we will look at how to create custom iterators in Rust.

To create a custom iterator in Rust, you need to implement the Iterator trait for your type. This trait requires you to implement the next method, which returns the next item in the iteration. You can also implement the size_hint method to provide information about the size of the iterator, and the fold method to allow the iterator to be folded into a single value.

Here is a simple example of a custom iterator that counts up from a given number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct CountUpFrom {
    start: u32,
}

impl Iterator for CountUpFrom {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.start < u32::MAX {
            self.start += 1;
            Some(self.start)
        } else {
            None
        }
    }
}

fn main() {
    let count_up_from = CountUpFrom { start: 10 };
    for i in count_up_from {
        println!("{}", i);
    }
}

This example creates a struct called CountUpFrom with a single field, start, which represents the number to start counting from. The CountUpFrom struct implements the Iterator trait, with u32 as the type of the items being iterated over. The next method increments the start field by one and returns it as an Option wrapped in a Some variant. If the start field has reached the maximum value of a u32, the next method returns None to indicate that the iteration is finished.

In the main function, we create an instance of CountUpFrom and use a for loop to iterate over it. This will print out the numbers 11 through u32::MAX to the console.

Custom iterators are a powerful and flexible tool in Rust, and can be used to create all sorts of interesting and useful iteration patterns. Give them a try in your next Rust project!

This post is licensed under CC BY 4.0 by the author.