Iterating through a collection
In order to implement a collection, we must provide a way to access each element in the collection, which can be accomplished using the int index value shown in the following code. We will implement a first in, first out (FIFO) order queue. We will provide a way to store the elements using a slice data structure. Lastly, we will implement a Next()
method to provide a way to traverse the elements in the collection.
In the following code, we define an interface for the Iterator
object. It has one method, Next()
, which will return the next element in the collection and a Boolean flag to indicate whether it's OK to continue iterating:
type CarIterator interface { Next() (value string, ok bool) } const INVALID_INT_VAL = -1 const INVALID_STRING_VAL = ""
Next, we define a collection object that has two properties: an int
index used to access the current element and a slice of strings, that is, the actual data in the collection:
type Collection struct { index...