Skip to content

Instantly share code, notes, and snippets.

@shenwei356
Created November 16, 2016 15:48
Show Gist options
  • Save shenwei356/44af553eb996fcf5ba25bea2c1ff1d15 to your computer and use it in GitHub Desktop.
Save shenwei356/44af553eb996fcf5ba25bea2c1ff1d15 to your computer and use it in GitHub Desktop.
generator-with-channel.go https://play.golang.org/p/xaKzUfd2sJ
package main
import (
"fmt"
)
type IntGenerator struct {
Chan chan int
n int
}
func NewIntGenerator() *IntGenerator {
g := &IntGenerator{make(chan int), 0}
go func() {
for {
select {
case g.Chan <- g.n:
g.n++
}
}
}()
return g
}
func (g *IntGenerator) Next() int {
return <-g.Chan
}
func main() {
g := NewIntGenerator()
fmt.Println(g.Next())
fmt.Println(g.Next())
fmt.Println(g.Next())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment