Junior
What are the types of channels in Go?
sobes.tech AI
Answer from AI
In Go, there are two main types of channels:
-
Unbuffered:
- Created without specifying buffer size:
make(chan int). - Send operation blocks until another goroutine performs a receive.
- Receive operation blocks until another goroutine performs a send.
- Provide synchronization between goroutines.
- Created without specifying buffer size:
-
Buffered:
- Created with a specified buffer size:
make(chan int, 10). - Send operation blocks only if the buffer is full.
- Receive operation blocks only if the buffer is empty.
- Allow asynchronous sending and receiving of data as long as there is space in the buffer.
- Created with a specified buffer size:
Channels can also be viewed in terms of direction:
- Bi-directional: Channels that are created by default with the ability to send and receive data.
- Directional: Channels explicitly declared for either sending (
chan<- T) or receiving (<-chan T). This helps enhance type safety and clarify intent in function signatures.
// Unbuffered channel
unbufferedChan := make(chan int)
// Buffered channel with buffer size 5
bufferedChan := make(chan string, 5)
// Send-only channel
sendOnlyChan := make(chan<- float64)
// Receive-only channel
receiveOnlyChan := make(<-chan bool)