SoFunction
Updated on 2025-03-03

Iterator mode explanation and code examples of Go design pattern

Go IteratorPattern explanation and code examples

With the help of iterators, the client can use an iterator interface to iterate through elements in different collections in a similar way.

Example

The main idea of ​​the iterator pattern is to extract the iterative logic behind the collection into different objects called iterators. This iterator provides a generic method that can be used to iterate on a collection without being affected by its type.

:gather

package main
type Collection interface {
	createIterator() Iterator
}

:Specific collection

package main
type UserCollection struct {
	users []*User
}
func (u *UserCollection) createIterator() Iterator {
	return &UserIterator{
		users: ,
	}
}

:Iterator

package main
type Iterator interface {
	hasNext() bool
	getNext() *User
}

:Specific iterator

package main
type UserIterator struct {
	index int
	users []*User
}
func (u *UserIterator) hasNext() bool {
	if  < len() {
		return true
	}
	return false
}
func (u *UserIterator) getNext() *User {
	if () {
		user := []
		++
		return user
	}
	return nil
}

:Client code

package main
type User struct {
	name string
	age  int
}

: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 := ()
	for () {
		user := ()
		("User is %+v \n", user)
	}
}

:Execution results

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

This is the article about the iterator mode explanation and code examples of Go design pattern. For more related content of Go iterator mode, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!