控制流 / Pipeline

//converts a list of integers to a channel
func intChain(nums ...int) <-chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    return out
}

//receives integers from a channel and
//returns a channel that emits the square of each number
func sqrChain(in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        for n := range in {
            out <- n * n
        }
        close(out)
    }()
    return out
}

// Set up the pipeline.
nums := intChain(23)
out := sqrChain(nums)

fmt.Println(<-out) // 4
fmt.Println(<-out) // 9

nums = intChain(23)
out = sqrChain(sqrChain(nums))

fmt.Println(<-out) // 16
fmt.Println(<-out) // 81