Rust, Software Development

The Iterator Design Pattern Example In Rust

This post shows how to use the Iterator design pattern in Rust without using the Iterator trait or any crate. Suppose we have a struct with multiple collections of various types that implement the same trait.

The Iterator Design Pattern Use Case

For this example, we have a use case to provide client codes with the names of prescribed and over-the-counter drugs in a list format. Moreover, we use the pallet concept to simulate an aggregate object with a complex internal data structure. Hypothetically, for our example, each Pallet can contain a list of prescribed and non-prescribed medicines. However, in reality, the content of any Pallet could be in a very complex structure or organization.

Instead of letting the client codes go through the internal collections, we provide them with a list of drug names.

Rust Traits And Other Structs

Whether the medicines are prescribed drugs or not, they all have names. Therefore, we can create a trait that their struct representatives can implement. In that way, we can retrieve their names.

Then, we create the individual structs for the drug types. Although they could contain more properties, we can stick with medicine names for simplicity.

Next, we implement a function in the Pallet struct that returns a list of drug names. This Rust function provides access to a simplified version of the Pallet internal data as per the Iterator design pattern.

Test Iterator Design Pattern Rust Codes

To test our example, consider the following Rust codes. First, the main function creates both lists of prescribed and over-the-counter medicines. Then, it makes a Pallet with those lists.

Next, we retrieve a single list of all drug names without worrying about the complexity of the Pallet’s internal data. That is the essence of the Iterator design pattern!

When we run all the codes, we get the following output.

In case we want to improve the content of the list, we only modify it in one place – the Pallet struct.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like