Senior
What happens when reading and writing to a closed channel?
sobes.tech AI
Answer from AI
In Go, when working with channels:
-
Reading from a closed channel: If the channel is closed and there are no more data, the read operation returns the zero value of the channel's type and
falseas the second return value (if used), indicating that the channel is closed. -
Writing to a closed channel: Attempting to write to a closed channel causes a 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
Thus, a closed channel can be safely read from as long as there is data in it, but writing to it is not allowed.