Junior — Middle
What is the difference between buffered and unbuffered channels?
sobes.tech AI
Answer from AI
In Go, channels can be buffered or unbuffered, and this affects the behavior of sending and receiving data.
-
Unbuffered channel — a channel without an internal buffer. The sender blocks until the receiver reads the value. Similarly, the receiver blocks if there is no value to read.
-
Buffered channel — has an internal buffer of fixed size. The sender blocks only if the buffer is full, and the receiver blocks if the buffer is empty.
Example of creating a buffered channel:
ch := make(chan int, 3) // buffer of 3 elements
Using buffered channels is useful when you need to smooth out the speed difference between sender and receiver, allowing the sender to continue working until the buffer is full.