Junior — Middle
How many times must a channel be closed in Go to avoid errors?
sobes.tech AI
Answer from AI
In Go, a channel must be closed exactly once, when no more data is expected to be sent to it. Closing a channel multiple times will cause a panic (runtime panic).
Important:
- The channel should be closed by the sender, not the receiver.
- If the channel is used for data transfer between goroutines, closing it signals that no more data will be sent.
Example:
ch := make(chan int)
go func() {
defer close(ch) // close the channel once
for i := 0; i < 5; i++ {
ch <- i
}
}()
for val := range ch {
fmt.Println(val)
}
In this example, the channel is closed once after all values are sent.