Channels are a way for goroutines to communicate with eachother. A channel type is defined with the keyword
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.
Related course: Introducing Go: Build Reliable, Scalable Programs
In this example there are two goroutines (f, f2). These goroutines communicate via a channel,
c chan string.
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.
$ go run example.go
- When do you need channels?
- How can you send data into a channel?
- How can you read data from a channel?