Golang — Iterator Pattern

Matthias Bruns
3 min readMar 23, 2023

In the world of software engineering, design patterns are quite common. One of the most popular patterns is the “Iterator Pattern” which is part of the “Gang of Four” patterns. This pattern is used to traverse a collection of objects without exposing its internal structure. In this article, we will discuss how to implement the Iterator Pattern in Golang.

Understanding the Iterator Pattern

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying implementation. The basic idea is to provide an interface for accessing the elements of a collection, and this interface is called the Iterator. The Iterator interface defines methods that allow us to traverse a collection, such as Next(), HasNext(), and Current(). The actual implementation of the traversal is encapsulated within the Iterator, and the client code just uses the Iterator to access the elements of the collection.

Implementing the Iterator Pattern in Golang

In Golang, we can implement the Iterator Pattern using an interface, which defines the methods that are required for traversing the collection. Here is an example of the Iterator interface:

type Iterator interface {
Next() interface{}
HasNext() bool
}

--

--

Matthias Bruns

Senior Freelancer & Technical Lead Working as a Golang developer since 2020. as a mobile developer since 2013. Focussed on architecture & testability.