Channels are a way for goroutines to communicate with eachother. A channel type is defined with the keyword chan.

Because goroutines run concurrently, they can’t simply pass data from one goroutine to another. Channels are needed.

How do channels work?

If you type c <- "message", “message” gets send to the channel. Then msg := <- c means receive the message and store it in variable msg.

Download PDF

Example

Goroutines

In this example there are two goroutines (f, f2). These goroutines communicate via a channel, c chan string.

In goroutine f(c chan string) we send a message into the channel. In goroutine f2(c chan string) the message is received, stored and printed to the screen.

package main

import "fmt"

func f(c chan string) {
c <- "f() was here"
}

func f2(c chan string) {
msg := <- c
fmt.Println("f2",msg)
}


func main() {
var c chan string = make(chan string)
go f(c)
go f2(c)

fmt.Scanln()
}
$ go run example.go
f2 f() was here

Exercises

  • When do you need channels?
  • How can you send data into a channel?
  • How can you read data from a channel?