Junior — Middle
When and how should a channel be closed in Go?
sobes.tech AI
Answer from AI
In Go, channels are used for data transfer between goroutines. A channel should be closed when you want to signal to receivers that no more data will be sent.
When to close a channel:
- When the sender has finished sending data and will not write to the channel anymore.
- Usually, the sender closes the channel, not the receiver.
How to close a channel:
Use the built-in function close():
ch := make(chan int)
// Sender
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch) // Close the channel after sending all data
}()
// Receiver
for val := range ch {
fmt.Println(val) // Receive data until the channel is closed
}
Important:
- A channel should only be closed once.
- If you close a channel and then try to send data to it, a panic will occur.
- Receivers can use the
for val := range chloop to read until the channel is closed.
If the channel is used only for signaling (e.g., notifications), it can also be closed so that all receivers are aware of the completion.