Middle+
Who should close the channel?
sobes.tech AI
Answer from AI
The channel should be closed by the creator who no longer intends to send data to it. This is important to avoid panic when attempting to send data to a closed channel and to allow recipients to correctly determine the end of the data stream.
Main rules:
- The sender closes the channel when it will no longer send values.
- Recipients should not close the channel.
- Closing the channel signals to recipients that no more data will be sent.
Example:
func producer(ch chan<- int) {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch) // Close the channel after sending all data
}
func consumer(ch <-chan int) {
for val := range ch {
fmt.Println(val)
}
// When the channel is closed, the loop ends
}
func main() {
ch := make(chan int)
go producer(ch)
consumer(ch)
}