Sobes.tech
Senior

What rules for working with channels should be known during development (closed, open, when what can be done)?

sobes.tech AI

Answer from AI

In Go, channels are a means of communication between goroutines, allowing the transfer of values and synchronization of execution.

Main rules for working with channels:

  • Creation: A channel is created with the make function, for example: ch := make(chan int).
  • Closing a channel: A channel can be closed with the close(ch) function. Only the sender should close the channel to avoid panics.
  • Sending and receiving:
    • You can send to a channel until it is closed.
    • You can receive from a channel even after it is closed — once all values are read, further reads will return the zero value and false as the second parameter.
  • When to close a channel:
    • Close the channel when you are sure no more sends will occur.
    • Closing a channel signals to receivers that no more data will be sent.
  • Not allowed:
    • Sending to a closed channel — this will cause a panic.
    • Closing a channel more than once — also causes a panic.

Example:

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

for val := range ch { // receive values until the channel is closed
    fmt.Println(val)
}

Thus, it is important to control who and when closes the channel to avoid errors and race conditions. A closed channel is a signal to receivers that no more data will be sent.