Is it possible to multiplex several channels into one?

后端 未结 3 1861
北海茫月
北海茫月 2021-02-14 00:29

The idea is to have a variable number of channels in a slice, push each value received through them into a single channel, and close this output channel once the last one of the

3条回答
  •  失恋的感觉
    2021-02-14 01:00

    I believe this snippet does what you're looking for. I've changed the signature so that it's clear that the inputs and output should only be used for communication in one direction. Note the addition of a sync.WaitGroup, you need some way for all of the inputs to signal that they have completed, and this is pretty easy.

    func combine(inputs []<-chan int, output chan<- int) {
      var group sync.WaitGroup
      for i := range inputs {
        group.Add(1)
        go func(input <-chan int) {
          for val := range input {
            output <- val
          }
          group.Done()
        } (inputs[i])
      }
      go func() {
        group.Wait()
        close(output)
      } ()
    }
    

提交回复
热议问题