github.com/packtpublishing/learning-functional-programming-in-go@v0.0.0-20230130084745-8b849f6d58c4/Chapter02/01_iterator/main.go (about)

     1  package main
     2  
     3  type IntIterator interface {
     4  	Next() (value string, ok bool)
     5  }
     6  const INVALID_INT_VAL = -1
     7  const INVALID_STRING_VAL = ""
     8  
     9  type Collection struct {
    10  	index int
    11  	List  []string
    12  }
    13  
    14  func (collection *Collection) Next() (value string, ok bool) {
    15  	collection.index++
    16  	if collection.index >= len(collection.List) {
    17  		return INVALID_STRING_VAL, false
    18  	}
    19  	return collection.List[collection.index], true
    20  }
    21  
    22  func newSlice(s []string) *Collection {
    23  	return &Collection{INVALID_INT_VAL, s}
    24  }
    25  
    26  func main() {
    27  	var intCollection IntIterator
    28  	intCollection = newSlice([]string{"CRV", "IS250", "Blazer"})
    29  	value, ok := intCollection.Next()
    30  	for ok {
    31  		println(value)
    32  		value, ok = intCollection.Next()
    33  	}
    34  }