Hooray! After 3 years of work, I've finally released the ebook on design patterns! Check it out »

Iterator in Go

Iterator is a behavioral design pattern that allows sequential traversal through a complex data structure without exposing its internal details.

Thanks to the Iterator, clients can go over elements of different collections in a similar fashion using a single iterator interface.

Conceptual Example

The main idea behind the Iterator pattern is to extract the iteration logic of a collection into a different object called iterator. This iterator provides a generic method of iterating over a collection independent of its type.

collection.go: Collection

package main

type collection interface {
	createIterator() iterator

userCollection.go: Concrete collection

package main

type userCollection struct {
	users []*user

func (u *userCollection) createIterator() iterator {
	return &userIterator{
		users: u.users,

iterator.go: Iterator

package main

type iterator interface {
	hasNext() bool
	getNext() *user

userIterator.go: Concrete iterator

package main

type userIterator struct {
	index int
	users []*user

func (u *userIterator) hasNext() bool {
	if u.index < len(u.users) {
		return true
	return false

func (u *userIterator) getNext() *user {
	if u.hasNext() {
		user := u.users[u.index]
		return user
	return nil

user.go: Client code

package main

type user struct {
	name string
	age  int

main.go: Client code

package main

import "fmt"

func main() {

	user1 := &user{
		name: "a",
		age:  30,
	user2 := &user{
		name: "b",
		age:  20,

	userCollection := &userCollection{
		users: []*user{user1, user2},

	iterator := userCollection.createIterator()

	for iterator.hasNext() {
		user := iterator.getNext()
		fmt.Printf("User is %+v\n", user)

output.txt: Execution result

User is &{name:a age:30}
User is &{name:b age:20}

Iterator in Other Languages

Design Patterns: Iterator in Java Design Patterns: Iterator in C# Design Patterns: Iterator in C++ Design Patterns: Iterator in PHP Design Patterns: Iterator in Python Design Patterns: Iterator in Ruby Design Patterns: Iterator in Swift Design Patterns: Iterator in TypeScript