Middle
What is a channel in Go? What types of channels are there? How do buffered and unbuffered channels differ?
sobes.tech AI
Answer from AI
A channel in Go is a data type used for passing values between goroutines, providing synchronization and data exchange.
Types of channels:
- Unbuffered channels — have no internal buffer; sending blocks until the receiver reads the value.
- Buffered channels — have an internal buffer of fixed size; sending blocks only if the buffer is full.
Differences:
- In unbuffered channels, the sender and receiver must be ready at the same time for transmission/reception, ensuring strict synchronization.
- In buffered channels, the sender can place multiple values into the buffer without waiting for the receiver, until the buffer is full.
Example of creating and using a buffered channel:
ch := make(chan int, 2) // buffer of 2 elements
ch <- 1
ch <- 2
// ch <- 3 // blocks until space is freed
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2