Sobes.tech
Senior

Mida juhtub, kui loed ja kirjutad suletud kanalil?

sobes.tech AI

Vastus AI-lt

In Go, when working with channels:

  • Reading from a closed channel: If the channel is closed and there are no data, the read operation returns the zero value of the channel type and false in the second return value (if used), indicating the channel is closed.

  • Writing to a closed channel: Attempting to write to a closed channel causes a panic (panic). This is a runtime error.

Example:

ch := make(chan int)
close(ch)

// Reading
v, ok := <-ch // ok == false, v == 0

// Writing
ch <- 1 // panic: send on closed channel

Therefore, a closed channel can be safely read from as long as it has data, but writing to it is not allowed.