What are channels in Go? The difference between buffered and unbuffered channels.
sobes.tech AI
Answer from AI
In Go, channels are a mechanism for passing data between goroutines, providing synchronization and message exchange.
Unbuffered channel is a channel without an internal buffer. Sending to such a channel blocks until another goroutine reads the value, and vice versa — reading blocks if there is no data in the channel. This ensures strict synchronization between sender and receiver.
Buffered channel has an internal buffer of fixed size. Sending to the channel blocks only if the buffer is full, and reading blocks if the buffer is empty. This allows some level of asynchrony between sender and receiver.
Example:
ch := make(chan int) // unbuffered channel
chBuf := make(chan int, 2) // buffered channel with a buffer of 2 elements
// Sending to an unbuffered channel blocks until someone reads
ch <- 1
// Sending to a buffered channel blocks only if the buffer is full
chBuf <- 1
chBuf <- 2
// Next send will block until someone reads
chBuf <- 3
Thus, the choice between buffered and unbuffered channels depends on synchronization and performance requirements.