Senior
What are channels in Go and what are they used for? What types of channels exist?
sobes.tech AI
Answer from AI
Channels in Go are a mechanism for passing data between goroutines, providing synchronization and communication.
Main features:
- Allow safe transfer of values between concurrently executing goroutines.
- Block the sender if the channel is full, and the receiver if the channel is empty.
Types of channels:
- Bidirectional (chan T): can send and receive data.
- Send-only (chan<- T): can only send data.
- Receive-only (<-chan T): can only receive data.
Example of using a channel:
ch := make(chan int) // bidirectional channel
// Sending in a goroutine
go func() {
ch <- 42
}()
// Receiving
val := <-ch
fmt.Println(val) // 42
Channels simplify communication and synchronization between goroutines, avoiding the need for explicit locks.