Channels

Duration: 20 min  •  Difficulty: Expert

If Goroutines are the way to run tasks concurrently, then Channels are the way they talk/exchange data with each other.

Analogy

Imagine Goroutines as relay runners. A Channel is the baton passed from one runner to another.

Rules

  • Sending data: channel <- data
  • Receiving data: data <- channel
  • Receiving data is Blocking. The program will stop and wait until data is sent.
  • MAIN.GO
    package main
    import "fmt"
    func main() {
    // Create a channel that carries string type data
    messages := make(chan string)
    // Anonymous Goroutine sending data
    go func() {
    messages <- "Hello from Goroutine!"
    }()
    // Main thread waits for data to arrive (Blocking)
    msgContent := <-messages
    fmt.Println(msgContent)
    }