Rust Lang

How to Use Rust Iterators

Iterators are a concrete feature in Rust. They are very useful when you need to iterate over a sequence of elements. For example, if you are looping over the items in an array or vector, you are using an iterator.

This article will discuss iterators in Rust, how they are implemented, and how to use them.

Rust Iterator

An iterator refers to a feature that allows you to “walk through” a sequence of elements. As mentioned, it could be iterating over each element in an array.

Iterators in Rust are lazy. This means that the iterator does not need to know beforehand the number of elements it will “walk through”. It determines the next element if requested.

Rust Iterator Trait

Iterators are implemented by the iterator trait defined in the Rust standard library. This means we can use the iterator type on primitive types or a custom collection by providing the type to trait and the next method.

The syntax for the iterator trait is as shown:

pub trait Iterator {

type Item;

fn next(&mut self) -> Option<Self::Item>;

}

To implement the iterator trait on custom types, we need to define the next method, which returns one item at a time wrapped as a Some() or None when the iteration is complete.

Consider the following code that implements an iterator for a custom struct:

structCount {
current_value: i32,
}
impl Count {
fnnew() ->Self {
Self {
current_value: 0,
        }
    }
}
implIteratorfor Count {
typeItem = i32;
fnnext(&mutself) ->Option {
ifself.current_value<5 {
self.current_value += 1;
returnSome(self.current_value);
        }
None
    }
}
fnmain() {

}

Here, we have a struct that has a value of i32. Next is a count constructor for the struct. We also implement an iterator for the struct using the next function. This returns the next element in the sequence.

Note: the return value is Option<Self::Item>.

This allows us to return None if there is no next item.

Then, we can use this iterator as:

For I in Count::new() {

println!"{”", i);

}

Conclusion

This article discussed the nature of the Rust iterator and its importance. In addition, we delved into the Rust iterator trait and the methods to implement the Rust iterator in custom types. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list