Sobes.tech
Middle

What is the difference between buffered and unbuffered channels? What happens when writing to a closed channel?

sobes.tech AI

Answer from AI

Channels in Go can be buffered or unbuffered, and this affects the behavior when sending and receiving data.

  • Unbuffered channel — this is a synchronous channel. Sending to such a channel blocks until someone reads the value from the channel. Similarly, reading blocks if there is no data in the channel.

  • Buffered channel — this is an asynchronous channel with limited capacity. Sending blocks only if the buffer is full, and reading blocks if the buffer is empty.

If you try to send to a closed channel, a panic occurs with the message "send on closed channel". This is a runtime error, so you should ensure the channel is not closed before sending.