DEV Community

Discussion on: What I learned this week: running functions concurrently

Collapse
 
ineedale profile image
Alex Leonhardt

So it turns out there is some simplification possible, by replacing

    go func() {
        for outputs != nil {
            fmt.Println("...")
            select {
            case m, ok := <-outputs:
                if !ok {
                    outputs = nil
                    break
                }
                fmt.Println(m)
            }
        }
    }()

with a so much simpler

    go func() {
        for m := range outputs {
            fmt.Println(m)
        }
    }()

ranging over the outputs channel will yield each message in the channel, even after it is closed, until all items have been iterated over, then we're done and the go-routine will return.