Sobes.tech
Senior

// 2 func merge(chans ...chan int) <-chan int { panic("not implemented") } func main() { a,b,c := make(chan int), make(chan int), make(chan int) out := merge(a,b,c) go func(){ for v := range out { println(v) } }() a <- 1 a <- 2 a <- 3 b <- 4 c <- 5 close(c) a <- 6 } Implement the function merge that takes multiple channels of integers and returns a single channel that merges the values from all input channels. The merged channel should close when all input channels are closed.

sobes.tech AI

Answer from AI

The merge function should accept multiple chan int channels and return a single channel into which all values from the input channels are sent. When all input channels are closed, the output channel should also close.

The implementation is usually built using sync.WaitGroup to track the closing of all channels and launching goroutines to read from each channel.

Example implementation:

func merge(chans ...chan int) <-chan int {
    var wg sync.WaitGroup
    out := make(chan int)

    // Function to copy values from one channel to out
    output := func(c chan int) {
        defer wg.Done()
        for v := range c {
            out <- v
        }
    }

    wg.Add(len(chans))
    for _, c := range chans {
        go output(c)
    }

    // Close out after all goroutines finish
    go func() {
        wg.Wait()
        close(out)
    }()

    return out
}

This approach guarantees that all values from the input channels will be sent to the output channel, and the output channel will close after all input channels are closed.

// 2 func merge(chans ...chan int) <-chan int {… - sobes.tech