Created
November 16, 2016 15:48
-
-
Save shenwei356/44af553eb996fcf5ba25bea2c1ff1d15 to your computer and use it in GitHub Desktop.
generator-with-channel.go https://play.golang.org/p/xaKzUfd2sJ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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