Middle+
Kes peaks kanali sulgema - kirjanik või lugeja?
sobes.tech AI
Vastus AI-lt
In Go, the channel should be closed by the sender, not the receiver. Closing the channel signals that no more values will be sent, and readers can correctly finish reading upon detecting the closed channel.
If the reader closes the channel and the sender continues to attempt to send, it will cause a panic. Therefore, the responsibility for closing the channel lies with the side that writes to it.
Example:
ch := make(chan int)
func() {
defer close(ch) // sender closes the channel
for i := 0; i < 5; i++ {
ch <- i
}
}()
for val := range ch {
fmt.Println(val) // reads until closure
}