How do I close channels correctly in Go?

In Go, closing a channel is an important operation that indicates that no more values will be sent on the channel. This allows other goroutines to detect when the channel has been closed and can help prevent deadlocks. It's important to note that you should only close a channel from the sending side and not from the receiving side or multiple goroutines concurrently.

How to Close Channels in Go

To close a channel, you can use the built-in close function. Here's a simple example:

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 } close(ch) // Closing the channel after sending all values }() go func() { for val := range ch { fmt.Println(val) // Reading values from the channel until it's closed } }() wg.Wait() // Wait for the goroutine to finish }

Go channels close channels goroutines programming concurrency