package main // A simple go iterator implementation. // Someone could use generics to make this more, well, generic. And // maybe define a Next() function on a channel receiver to abstract // away needing the channel <- operator to get the next item and // and handle the iterator ending cleanly. This uses range which // already knows how to handle streaming values from channels. // // github user: thwarted import ( "fmt" ) // upto returns an iterator that emits integers up to the given max func upto(max int) chan int { c := make(chan int) yield := func(i int) { c <- i } go func() { for i := range max { yield(i) } close(c) }() return c } // powersOf2 returns an iterator that emits the powers of 2 up to max func powersOf2(max uint) chan uint { c := make(chan uint) yield := func(i uint) { c <- i } go func() { var cur uint = 1 for cur < max { yield(cur) cur *= 2 } close(c) }() return c } func main() { myiterator := upto(10) for i := range myiterator { fmt.Println("upto emitted ", i) } fmt.Println() for i := range powersOf2(3000) { fmt.Println("powersOf2 emitted ", i) } }