How do I avoid sending on a closed channel in Go?

In Go, sending on a closed channel will result in a runtime panic. To avoid this, you need to ensure that the channel is open before sending a value to it. There are various strategies to deal with this issue, such as using a boolean flag, utilizing the 'select' statement, or implementing a function that verifies the channel state. Below is an example illustrating how to avoid sending on a closed channel.

package main import ( "fmt" "sync" ) func main() { ch := make(chan int) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for i := 0; i < 5; i++ { ch <- i // sending data to the channel } close(ch) // closing the channel after sending }() go func() { for { val, ok := <-ch // check if the channel is still open if !ok { break // exit the loop if the channel is closed } fmt.Println(val) // process the received value } }() wg.Wait() // wait for all goroutines to finish }

Go channels sending on closed channel avoid panic concurrency goroutines