Created
January 19, 2019 04:55
-
-
Save miguelmota/7be1f7e47bc5910678861b1eb0783a34 to your computer and use it in GitHub Desktop.
Golang javascript-like generator
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" | |
func Generator() chan string { | |
c := make(chan string) | |
go func() { | |
c <- "hello" | |
c <- "world" | |
close(c) | |
}() | |
return c | |
} | |
func main() { | |
gen := Generator() | |
for true { | |
value, more := <-gen | |
fmt.Println(value, more) | |
if !more { | |
break | |
} | |
} | |
// alternatively | |
for value := range Generator() { | |
fmt.Println(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment