Sobes.tech
Junior — Middle

Kui sageli tuleb Go-s kanal sulgeda, et vältida vigu?

sobes.tech AI

Vastus AI-lt

In Go, it is necessary to close a channel exactly once, when no more data is planned to be sent to it. Closing the channel multiple times will lead to a panic (runtime panic).

Important:

  • The person writing to the channel should close it, not the one reading.
  • 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)
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 have been sent.