Last active
March 4, 2016 23:32
-
-
Save OutOfBrain/d41fe8bd0307a777867f to your computer and use it in GitHub Desktop.
Create a generator in go - similar to yield in python
This file contains hidden or 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" | |
| 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