Sobes.tech
Junior — Middle

Where in the code should the channel be closed?

sobes.tech AI

Answer from AI

In Go, a channel should be closed where it is created and where no more data is planned to be sent. Usually, this is done by the sender to signal to receivers that no more data will be sent.

Important:

  • Receivers can check for channel closure when reading.
  • Only the sender should close the channel to avoid panics.

Example:

ch := make(chan int)
go func() {
    defer close(ch) // close the channel after sending all data
    for i := 0; i < 5; i++ {
        ch <- i
    }
}()

for val := range ch {
    fmt.Println(val) // receive data until the channel is closed
}
Where in the code should the channel be closed… - sobes.tech