Skip to content

Instantly share code, notes, and snippets.

@betandr
Created December 30, 2019 13:51
Show Gist options
  • Save betandr/4d88e4a27fdaca18ec72b303036bdad6 to your computer and use it in GitHub Desktop.
Save betandr/4d88e4a27fdaca18ec72b303036bdad6 to your computer and use it in GitHub Desktop.
Simple pipeline example using Go channels
package main
import "fmt"
// first adds 20 integers in sequence to a channel then closes
// it, signalling all of the writing is done.
func first(out chan<- int) {
for x := 0; x < 20; x++ {
out <- x
}
close(out)
}
// second reads integers from the in channel until the channel is
// closed, it adds 10 to each one, then writes the result to the
// out channel then closes that, signalling all of the writing is
// done.
func second(out chan<- int, in <-chan int) {
for v := range in {
out <- v + 10
}
close(out)
}
// third reads the results and prints each one
func third(in <-chan int) {
for v := range in {
fmt.Println(v)
}
}
// simple pipeline example using channels
func main() {
source := make(chan int)
result := make(chan int)
go first(source)
go second(result, source)
third(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment