Lesson 33 of 38 · Concurrency
Go Channels: Communicating Between Goroutines
In the last lesson every goroutine wrote to its own slice index — fine for simple jobs, but most concurrent programs need goroutines to talk to each other: hand over results, signal that work is done, pass jobs along. Go's answer is the channel, a typed pipe that connects goroutines.
Sending and receiving
Create a channel with make, send a value with ch <- v and receive one with <-ch. The arrow shows which way the data flows:
package main
import "fmt"
func main() {
ch := make(chan string)
go func() {
ch <- "ping" // send
}()
msg := <-ch // receive
fmt.Println(msg)
}
ping
A channel carries values of one type: chan int, chan string, chan error… It must be created with make: the zero value of a channel type is nil, and a nil channel blocks forever on every send and receive.
Unbuffered channels synchronise
make(chan T) creates an unbuffered channel: it stores nothing. A send blocks until another goroutine receives, and a receive blocks until another goroutine sends. Both sides meet, the value changes hands, and both continue. So a channel is a synchronisation point as well as a pipe: above, main can't print before the goroutine has sent — no WaitGroup needed.
The flip side: if nobody ever receives, the sender waits forever. When every goroutine is stuck like this, the Go runtime stops the program:
func main() {
ch := make(chan int)
ch <- 1 // blocks: no other goroutine will ever receive
fmt.Println(<-ch)
}
fatal error: all goroutines are asleep - deadlock!
Directional channel types
A function signature can restrict a channel to one direction: a chan<- int may only be sent to, a <-chan int may only be received from.
func produce(n int, out chan<- int) {
for i := 1; i <= n; i++ {
out <- i * i
}
}
func consume(n int, in <-chan int) int {
total := 0
for i := 0; i < n; i++ {
total += <-in
}
return total
}
func main() {
ch := make(chan int)
go produce(3, ch)
fmt.Println(consume(3, ch))
}
14
A plain chan int converts to either direction automatically. Using a channel the wrong way is a compile error (invalid operation: cannot receive from send-only channel), so the types both document and enforce who sends and who receives.
Collecting N results
A very common pattern: start N goroutines that each send exactly one result, then receive exactly N times.
results := make(chan int)
for _, n := range []int{2, 3, 4} {
go func() {
results <- n * n
}()
}
total := 0
for i := 0; i < 3; i++ {
total += <-results
}
fmt.Println(total) // 29
The results arrive in whatever order the goroutines finish, so combine them in an order-independent way (a sum, a count, a map) — or send the index along with the value when the order matters.
This is a famous Go proverb in action: "Don't communicate by sharing memory; share memory by communicating." Instead of several goroutines updating one shared variable, each one sends its value, and a single goroutine owns the total.
Common mistakes
- Sending and receiving in the same goroutine on an unbuffered channel: the send waits for a receiver that never comes — deadlock.
- Receiving more values than were sent: the extra receive blocks forever. Count your sends and receives.
- Assuming an order: values from different goroutines can arrive in any order.
- Declaring without
make:var ch chan intis a nil channel, and it blocks forever.
Assignment
Add up a slice in parallel. Each goroutine sums one piece and sends its partial sum through a channel; the caller receives the partial sums and adds them up.
SumPart(part []int, out chan<- int)adds up the numbers inpartand sends the sum onout. It sends exactly once — also for an empty part, whose sum is0.SumParallel(nums []int, parts int) intsplitsnumsintopartspieces, runsSumPartfor every piece in its own goroutine, receives exactlypartspartial sums from one channel and returns their total. Ifpartsis less than 1, use 1. Piecep(counting from 0) isnums[p*len(nums)/parts : (p+1)*len(nums)/parts]— these bounds are always valid, even with more parts than numbers (some pieces are then empty).
SumParallel([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 3) // 55 (pieces 1–3, 4–6 and 7–10)Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .