Channels are a fundamental concurrency primitive in Go, providing a type-safe way for goroutines to communicate and synchronize. They act as pipes, allowing data to be sent and received between concurrent processes.
To create a channel, use the make()
function with the chan
keyword:
ch := make(chan int)
Sending and receiving data through channels is done using the <-
operator:
// Send data
ch <- 42
// Receive data
value := <-ch
Go supports two types of channels:
Create a buffered channel by specifying its capacity:
bufferedCh := make(chan int, 3)
Channels can be directional, restricting their use to either sending or receiving:
func sendOnly(ch chan<- int)
func receiveOnly(ch <-chan int)
Channels can be closed to signal that no more values will be sent:
close(ch)
Check if a channel is closed when receiving:
value, ok := <-ch
if !ok {
fmt.Println("Channel closed")
}
The select statement allows you to work with multiple channels simultaneously:
select {
case v1 := <-ch1:
fmt.Println("Received from ch1:", v1)
case v2 := <-ch2:
fmt.Println("Received from ch2:", v2)
case <-time.After(1 * time.Second):
fmt.Println("Timeout")
}
Channels are a powerful tool for concurrent programming in Go. They provide a safe and efficient way to communicate between goroutines, enabling developers to build robust and scalable concurrent applications. By mastering channels, you'll be well-equipped to handle complex concurrency scenarios in your Go projects.