/* * Using a closure to simulate an iterator. If you language does not have an * iterator, but does do closures. Really a useless thing in Go * as iterators work fine * @author gtowell * created: July 30, 2021 */ package main import "fmt" // the type of the iterator function // note the use of two return values. // The first gives the next value of the slice // The second indicates where that value should actually be // used (i.e., the slice actually had another value) type CIter func() (int,bool) // the function to generator the closure containing function func makeClo(slic []int) CIter { idx:=0 fun := func() (int,bool) { if idx>=len(slic) { return 0,false } x := slic[idx] idx++ return x,true } return fun } func main() { var islic []int // fill a slice with things for i:=5; i<25; i++ { islic = append(islic, i) } clo := makeClo(islic) // the function // a while loop over the closure for { c,more:=clo() if !more { break; } fmt.Printf("CLO: %v\n", c) } }