How to safely close multiple channels using a select statement and sync in Golang?

To safely close multiple channels using a select statement and sync in Golang, you can follow these steps:

  1. Import the required packages.
import ( "sync" )
  1. Declare the channels and a wait group.
ch1 := make(chan bool) ch2 := make(chan bool) wg := sync.WaitGroup{}
  1. Create a function to safely close the channels.
func safeClose(ch chan bool) { defer wg.Done() // Notify wait group that the function is done select { case _, ok := <- ch: if ok { close(ch) // Close the channel if it still open } default: // Channel is already closed } }
  1. Initialize the wait group.
wg.Add(2) // Number of channels to close
  1. Start goroutines to close the channels.
go safeClose(ch1) go safeClose(ch2)
  1. Wait for the goroutines to finish.
wg.Wait() // Wait until all the goroutines are done

By following these steps, you can safely close multiple channels using a select statement and sync in Golang.