Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).
We will create a travel guide with entries on the routes. And we will get information about each route.
-
First, we will create our
Iteratorinterface. This interface will check if the next element exists and receive the element.// route/route.go type Iterator interface { HasNext() bool GetNext() *Route }
-
Now we need our structure with information about a route.
// route/route.go type Route struct { Name string TravelTime int }
-
And now, we will use our interface to iterate to the routes.
// route/route.go type Routes struct { Routes []Route index int } func (r *Routes) HasNext() bool { return r.index < len(r.Routes) } func (r *Routes) GetNext() *Route { if r.HasNext() { val := &r.Routes[r.index] r.index++ return val } return nil }