Skip to content

Instantly share code, notes, and snippets.

@OutOfBrain
Last active March 4, 2016 23:32
Show Gist options
  • Select an option

  • Save OutOfBrain/d41fe8bd0307a777867f to your computer and use it in GitHub Desktop.

Select an option

Save OutOfBrain/d41fe8bd0307a777867f to your computer and use it in GitHub Desktop.
Create a generator in go - similar to yield in python
package main
import "fmt"
func countGenerator() func() int{
// state
c := make(chan int)
var i int
// generator
go func(){
for {
c <- i
i++
}
}()
// reader
return func() int{
return <-c
}
}
func main() {
c := countGenerator()
c2 := countGenerator()
fmt.Println(c(), c(), c()) // 0 1 2
fmt.Println(c2(), c2(), c()) // 0 1 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment