Building Reusable and Generic Iterators in Go
Radhakishan Surwase
Senior Technical Lead | Golang Expert | Microservices Architect | Cloud-Native Enthusiast | Kubernetes & Docker | Building Scalable Systems
The iterator pattern is a powerful tool for traversing collections, such as lists, arrays, and maps, without exposing their underlying representations. While Go doesn't have a built-in iterator interface like some other languages, it's possible to implement this pattern using custom structs and methods. With the introduction of generics in Go 1.18, creating reusable and generic iterators has become even more accessible.
Implementing a Generic Slice Iterator
Slices are one of the most common data structures in Go. Implementing an iterator for a slice allows you to traverse its elements in a clean and reusable manner. Here's how you can do it:
This SliceIterator is a reusable solution for iterating over slices of any type. It works by keeping track of the current index and providing methods to check if there are more elements (HasNext) and to retrieve the next element (Next).
Extending the Pattern to Maps
Maps are a bit trickier since they are unordered collections of key-value pairs. However, we can still create a reusable and generic iterator for maps. Here's an example:
In this MapIterator, we maintain a slice of keys extracted from the map to enable ordered iteration. The HasNext and Next methods then allow us to traverse the map's key-value pairs in a consistent manner, even though the order of iteration is inherently undefined in Go maps.
Conclusion
By implementing reusable and generic iterators for both slices and maps, you can traverse collections in Go in a clean and structured way. The use of generics makes these iterators flexible, allowing them to be used with any data type. Whether you're working with sequential data in slices or key-value pairs in maps, these iterator patterns provide a powerful toolset for managing iteration in your Go applications.
Director / Director of Engineering / Head of Software Engineering / Engineering Manager/ Agile Leader
7 个月Nice and simple