How to Listen N Channels in Go

To listen to N channels in Go, you can create an array or slice of channels with the desired length and then extend the select statement with more case branches to cover all channels.

Here’s an example of listening to 3 channels, but you can easily extend it to N channels:

package main

import (
  "fmt"
  "time"
)

func main() {
  // Create 3 channels
  ch1 := make(chan string)
  ch2 := make(chan string)
  ch3 := make(chan string)

  // Start 3 goroutines to send data to the channels
  go func() {
    time.Sleep(1 * time.Second)
    ch1 <- "Message from channel 1"
  }()
  go func() {
    time.Sleep(2 * time.Second)
    ch2 <- "Message from channel 2"
  }()
  go func() {
    time.Sleep(3 * time.Second)
    ch3 <- "Message from channel 3"
  }()

  // Create a slice of channels
  channels := []chan string{ch1, ch2, ch3}

  // Create a counter to track the number of received messages
  receivedCount := 0

  // Loop until all channels have sent their messages
  for receivedCount < len(channels) {
    select {
      case msg := <-ch1:
        fmt.Println("Received:", msg)
        receivedCount++
      case msg := <-ch2:
        fmt.Println("Received:", msg)
        receivedCount++
      case msg := <-ch3:
        fmt.Println("Received:", msg)
        receivedCount++
   }
  }
}

Remember that having too many channels in a single select statement can make the code difficult to maintain. Consider using a dynamic approach or structuring your code differently if you need to manage many channels.

That’s it.

Leave a Comment