How to Pipeline Data with Channels in Go

Pipe data between Go goroutines safely by sending values into a channel and receiving them with a range loop.

You pipeline data in Go by creating a channel, launching a goroutine to send data into it, and reading from it in the main thread until the channel closes.

package main

import "fmt"

func main() {
    ch := make(chan int)
    go func() {
        for i := 1; i <= 3; i++ {
            ch <- i
        }
        close(ch)
    }()
    for n := range ch {
        fmt.Println(n)
    }
}