Middle+
What happens if you write to a closed channel in Go?
sobes.tech AI
Answer from AI
If you try to write a value to a closed channel in Go, a panic will occur with the message "send on closed channel". This is because a closed channel no longer accepts new values.
Example:
ch := make(chan int)
close(ch)
ch <- 1 // panic: send on closed channel
Important:
- Reading from a closed channel is possible and will return the zero value and false if the channel is empty.
- Writing to a closed channel always results in a panic.
Therefore, before writing to a channel, you need to be sure that it is not closed, or use other synchronization mechanisms.