Channels
Channels are the pipes that connect concurrent Goroutines. You can send values into channels from one goroutine and receive those values in another goroutine.
Creating a Channel
Channels are typed. You use the make built-in to create them:
ch := make(chan int) // Creates a channel of integers
Sending and Receiving
You use the <- operator to send or receive data.
package main
import "fmt"
func main() {
ch := make(chan string)
go func() {
// Send to channel
ch <- "Ping from Goroutine!"
}()
// Receive from channel
msg := <-ch
fmt.Println(msg)
}
Buffered vs Unbuffered
By default, channels are unbuffered, meaning that sends block until the receiver is ready. You can create buffered channels that accept a limited number of values without a receiver:
ch := make(chan int, 100) // Buffer size of 100
Channels are a fundamental piece of Go’s concurrency model. To understand where they fit in the broader language, refer back to the Introduction.