Senior
What are the differences between the types of channels in Go?
sobes.tech AI
Answer from AI
In Go, channels are of three types based on data transfer direction:
- Bidirectional channels — regular channels that can be used for both sending and receiving data.
ch := make(chan int) // bidirectional channel
ch <- 10 // send
val := <-ch // receive
- Send-only channels — declared with the direction
chan<-, allowing only sending data, receiving from them is impossible.
var sendOnly chan<- int = ch
sendOnly <- 5 // sending is allowed
// val := <-sendOnly // compile error
- Receive-only channels — declared with the direction
<-chan, allowing only receiving data, sending is prohibited.
var recvOnly <-chan int = ch
val := <-recvOnly // receiving is allowed
// recvOnly <- 5 // compile error
Using directional channels helps improve type safety and makes the code more readable by explicitly indicating where the channel is used only for sending or receiving.