The Programming Shortcut: Go
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about concurrency by message passing.
Boring on purpose
Go is a language made for big teams who want to write plain programs.
It was started at Google in 2007 by Robert Griesemer, Rob Pike and Ken Thompson, and went public in 2009. They wanted a language that compiled fast, ran fast, and stayed readable in a code base far too big for any one person to hold in their head. So they built one with very few features, one way to format your code, and almost nothing to be clever with.
People sometimes call Go boring. Its fans agree, and mean it as praise. Boring code is code the next person can read.
A boring language gets out of your way. You’ll recognize most Go the moment you see it. And that leaves room for the one part of Go that is not boring at all: it was built from the first day to do several things at once. Go made that part of the language itself, with a keyword and a type, and gave it a motto. By the end of this article you’ll know what the motto means and why it works.
You can already read Go
Here is what carries over. Read it row by row; where the columns look alike, you can stop thinking.
| What you know | lux | Go |
|---|---|---|
| where the program starts | func main() | func main() |
| a record | struct Job { id: int } | type Job struct { id int } |
| a new variable | let x = 3, var x = 3 | x := 3 |
| a loop over an array | for job in jobs | for _, job := range jobs |
| printing | print(a, b) | fmt.Println(a, b) |
| a value that might be missing | Option | the zero value, or nil |
| an error you expect | Result | a value, err pair |
| several things at once | (none) | goroutines and channels |
The last row is the new one, and it’s the rest of this article. Two rows above it
differ more than they look: Go has no Option or Result type. A missing value is a variable’s
zero value (0, "", or nil, meaning “points at nothing”), and a function that
can fail hands back two things, the answer and an error, which you check with an
ordinary if. That’s the idea of errors as plain values, explained more fully in
the Rust article.
If you learned lux, there’s an even shorter shortcut. lux convert go turns your
lux program into Go source, so you can read something you wrote, in Go, before you
write a line of Go yourself.
Edit, run, repeat
The one tool for this article is the go command. Install Go from
go.dev/doc/install, then check it with
go version.
Make a folder, and tell Go it holds a program:
mkdir squares
cd squares
go mod init squares
go mod init writes a small file called go.mod, which names your program (Go
calls it a module) and records the Go version. You won’t need to touch it.
Now the program. If you know lux, here is one you could have written:
struct Job {
id: int
size: int
}
func work(job: Job) -> int {
return job.size * job.size
}
func main() {
let jobs = [Job(id: 1, size: 3), Job(id: 2, size: 5), Job(id: 3, size: 7)]
var total = 0
for job in jobs {
let answer = work(job)
print("job", job.id, "->", answer)
total += answer
}
print("total:", total)
}
Save it as squares.lux and run lux convert go squares.lux > main.go. If you
don’t know lux, save this as main.go instead. It’s what the converter writes:
package main
import "fmt"
type Job struct {
id int
size int
}
func work(job Job) int {
return job.size * job.size
}
func main() {
jobs := []Job{Job{id: 1, size: 3}, Job{id: 2, size: 5}, Job{id: 3, size: 7}}
total := 0
for _, job := range jobs {
answer := work(job)
fmt.Println("job", job.id, "->", answer)
total += answer
}
fmt.Println("total:", total)
}
Two small things are new. range hands you two values on each pass, the position
and the element, and the underscore _ says “I don’t need the position.” And
fmt is the package that prints; import "fmt" brings it in.
Then run it:
go run .
job 1 -> 9
job 2 -> 25
job 3 -> 49
total: 83
The dot means “the program in this folder.” You’ll do that a lot: change
main.go, run go run ., read what comes back. Every example
below is a whole program, so you can paste any of them over main.go and run it.
Several things at once
Your squares program does one thing at a time. It works on job 1, then job 2, then job 3. Nothing starts until the thing before it is finished.
That’s fine when each job takes a millionth of a second. It’s less fine when each job is a web request that takes half a second, mostly spent waiting for a server somewhere to answer. A program that does one thing at a time spends most of its life waiting.
Think of a cook making soup and bread. A cook who does one thing at a time puts the soup on and stands watching the pot for an hour, then starts the bread. A real cook puts the soup on, starts the bread while it simmers, and checks on both.
That second cook is doing concurrent work. Concurrency means a program is built from several pieces of work that can be in progress at the same time, each one moving forward whenever it can. It’s related to parallelism, which means work happening at literally the same instant on different processor cores. A concurrent program can run in parallel if your machine has the cores to spare, but the idea is about how you organize the work, not how many cores you have. Rob Pike, one of Go’s designers, gave a good talk on the difference.
Concurrency has a reputation for being hard, and for once the reputation is fair. The hard part is almost never starting several pieces of work. The hard part is letting them talk to each other without stepping on each other’s toes. Go’s answer to that is the idea this article is about: message passing. Pieces of work don’t share things. They send each other messages.
If you learned lux, every program you wrote there had one line of work going on at a time, top to bottom. lux left goroutines out on purpose, because they belong to Go alone. Go keeps that one line of work, and lets you start more of them.
go starts something new
In Go, one of those independent pieces of work is called a goroutine. It is a
function call that runs on its own, alongside everything else. You start one by
putting the word go in front of a call:
package main
import "fmt"
func greet(name string) {
fmt.Println("hello,", name)
}
func main() {
go greet("goroutine")
fmt.Println("main is done")
}
Run it. You’ll almost certainly see only this:
main is done
Where did the greeting go? go greet(...) started the greeting and returned
immediately, without waiting for it. main printed its line and returned, and when
main returns, the program ends. Every other goroutine stops right where it is,
mid-sentence if need be.
Goroutines are cheap. The Go FAQ says a new one starts with a few kilobytes of memory, and that “it is practical to create hundreds of thousands of goroutines” in one program. So starting them is the easy part, as promised. What we’re missing is a way to wait for one, and a way to get an answer back from it. In Go, those turn out to be the same thing.
A channel is a handoff
A channel is a pipe that one goroutine puts values into and another takes values
out of. It has a type, like everything in Go: a chan string carries strings, a
chan int carries ints. You make one with make:
done := make(chan string)
Two operations use the arrow <-, which points the way the value moves. done <- "soup" sends a value into the channel. <-done receives a value out of it.
A channel made this way, an unbuffered channel, holds nothing at all. A send waits until some other goroutine is ready to receive, and a receive waits until someone sends. The two goroutines meet, the value passes from one hand to the other, and both carry on. So a channel does two jobs at once: it delivers a value, and it tells both sides that the other one got there. Effective Go, the language’s own style guide, puts it this way: unbuffered channels “combine communication—the exchange of a value—with synchronization.”
Here is the cook, with two dishes:
package main
import (
"fmt"
"time"
)
func cook(dish string, done chan string) {
time.Sleep(100 * time.Millisecond)
done <- dish + " is ready"
}
func main() {
start := time.Now()
done := make(chan string)
go cook("soup", done)
go cook("bread", done)
fmt.Println(<-done)
fmt.Println(<-done)
fmt.Println("took", time.Since(start).Round(time.Millisecond))
}
time.Sleep pauses a goroutine, standing in for slow work. Each dish takes a tenth
of a second, and there are two of them, so cooking them one after the other would
take two tenths. Run it a few times:
bread is ready
soup is ready
took 100ms
Both dishes cooked at once, so the meal took one tenth of a second. And sometimes soup comes first, sometimes bread. That’s not a bug. The two goroutines are racing to the channel, and whichever gets there first is received first. In a concurrent program, results arrive in the order they finish, not the order you started them.
Notice also that main waited, this time. Each <-done held main still until a
dish arrived, so it couldn’t run off and end the program early. Receiving was the
waiting.
Your program, three jobs at a time
Now go back to the squares program and give each job its own goroutine. Instead of
returning its answer, work sends it down a channel:
package main
import "fmt"
type Job struct {
id int
size int
}
func work(job Job, results chan int) {
results <- job.size * job.size
}
func main() {
jobs := []Job{Job{id: 1, size: 3}, Job{id: 2, size: 5}, Job{id: 3, size: 7}}
results := make(chan int)
for _, job := range jobs {
go work(job, results)
}
total := 0
for range jobs {
answer := <-results
fmt.Println("got", answer)
total += answer
}
fmt.Println("total:", total)
}
The first loop starts three goroutines and moves on without waiting. The second
loop runs once per job (for range jobs repeats that many times without naming
anything) and receives one answer each time. The answers may arrive in any order,
and the total is always 83, because addition doesn’t care about order.
Don’t share, send
Look at who touches total in that program. Only main does. The three workers
never see it. They compute a number and send it, and main adds it up.
That’s on purpose, and it’s the motto. Effective Go says:
Do not communicate by sharing memory; instead, share memory by communicating.
The first half describes the way most concurrent programs were written for decades. Several pieces of work all reach into the same variable, and they each have to be careful not to change it at the same moment as somebody else. Being careful is easy to get wrong, and the mistakes are invisible most of the time.
The second half is Go’s suggestion. Give each piece of data one owner. If anyone else wants it changed, or wants to know its value, they send the owner a message. When only one goroutine ever touches a variable, there is nothing to be careful about.
Once you see this shape, you’ll spot it in other languages too. Erlang and Elixir
build everything from small processes that each own their data and send messages
to each other’s mailboxes. Rust’s standard library has channels with a sender end
and a receiver end. A web page can hand work to a background worker and get the
answer back with postMessage. The spelling changes. The idea is the same: work
that doesn’t share variables, joined by sends and receives.
Closing time
Sometimes the receiver doesn’t know how many values are coming. For that, the
sender can close the channel, which means “there’s nothing more.” A for loop
with range over a channel receives values until the channel is closed, then
stops:
package main
import "fmt"
func countTo(n int, out chan int) {
for i := 1; i <= n; i++ {
out <- i
}
close(out)
}
func main() {
numbers := make(chan int)
go countTo(3, numbers)
for n := range numbers {
fmt.Println(n)
}
fmt.Println("no more numbers")
}
Closing is the sender’s job, never the receiver’s. Sending on a closed channel crashes the program, so only the side that knows when the work is finished should close.
Waiting forever
Because sends and receives wait for each other, it’s possible to wait for someone who will never come. Here’s the smallest way to do it:
package main
import "fmt"
func main() {
ch := make(chan string)
ch <- "hello"
fmt.Println(<-ch)
}
main sends, and waits for a receiver. The only receiver is the next line of
main, which can’t run until the send is done. Nothing can ever move. That’s a
deadlock, and Go notices:
fatal error: all goroutines are asleep - deadlock!
Go can only notice when every goroutine is stuck. If one goroutine is waiting forever while others keep running, nothing complains. That stuck goroutine just sits there, using a little memory, for the rest of the program’s life. It’s called a goroutine leak, and it’s a common quiet bug in concurrent Go.
There’s another way out of this particular deadlock. Give the channel a buffer,
room to hold some values with nobody receiving yet, by passing a size to make:
package main
import "fmt"
func main() {
ch := make(chan string, 1)
ch <- "hello"
fmt.Println(<-ch)
}
Now the channel is a mailbox with room for one letter. The send drops the value in and moves on, and the receive picks it up later. A send only waits once the buffer is full.
Waiting for whichever comes first
One last tool. A select statement waits on several channels at once and takes
whichever one is ready first. It looks like a switch, with a send or receive in
each case. A common use is giving up on slow work:
package main
import (
"fmt"
"time"
)
func cook(dish string, wait time.Duration, done chan string) {
time.Sleep(wait)
done <- dish + " is ready"
}
func main() {
done := make(chan string, 1)
go cook("stew", 500*time.Millisecond, done)
select {
case msg := <-done:
fmt.Println(msg)
case <-time.After(200 * time.Millisecond):
fmt.Println("gave up waiting for the stew")
}
}
time.After hands back a channel that receives a single value once the time is up.
Whichever channel delivers first wins. If both are ready at the same moment, Go
picks one at random, so your program can’t quietly depend on the order you wrote
the cases in. (The done channel has a buffer of one so the stew’s goroutine can
still drop off its message after nobody is listening, instead of waiting forever.)
That’s the core of message passing in Go: start work with go, connect it with
channels, close a channel when you’re done sending, and select when you need to
wait for more than one thing.
The compiler won’t stop you
Go gives you channels. It doesn’t make you use them.
Nothing in Go stops two goroutines from reaching into the same variable. Here are four goroutines, each adding to one shared counter a hundred thousand times:
package main
import "fmt"
var count int
func addMany(done chan bool) {
for range 100_000 {
count++
}
done <- true
}
func main() {
done := make(chan bool)
for range 4 {
go addMany(done)
}
for range 4 {
<-done
}
fmt.Println("count:", count)
}
(for range 4 repeats four times, and var count int declares a variable
outside any function, so every function can see it.)
It compiles without a word of complaint. The answer should be 400,000. On three runs on my machine it printed 199,130, then 400,000, then 226,630.
The reason is that count++ isn’t one step. It reads count, adds one, and writes
the result back. Two goroutines can both read 41, both add one, and both write 42,
and one of the additions is gone. This is a data race: two goroutines touching the
same memory at the same time, at least one of them writing, with nothing deciding
who goes first. Its symptoms come and go from run to run, which makes it miserable
to track down.
Some languages refuse to compile this. Rust’s compiler, for one, won’t let two pieces of concurrent work change the same value unless you prove it’s safe; its rules about who owns what are the subject of the Rust article. Go made a different trade. It trusts you, keeps the language small, and gives you a detector instead. Add one flag to the same command you already use:
go run -race .
==================
WARNING: DATA RACE
Read at 0x000000607098 by goroutine 11:
main.addMany()
main.go:9 +0x39
...
Found 2 data race(s)
exit status 66
The race detector watches the program while it runs and tells you the line where two goroutines collided. It only sees races that happen during that run, so it can’t promise your program is clean, but it catches a great deal. On most systems it needs a C compiler installed, and its documentation says which.
Beware of using channels for everything. Once channels click, it’s tempting to route every bit of shared state through one, with a goroutine standing guard over a counter. For a counter, that’s a lot of machinery. The plain answer is a mutex (short for “mutual exclusion”), a lock that only one goroutine can hold at a time:
package main
import (
"fmt"
"sync"
)
var (
count int
mu sync.Mutex
)
func addMany(done chan bool) {
for range 100_000 {
mu.Lock()
count++
mu.Unlock()
}
done <- true
}
func main() {
done := make(chan bool)
for range 4 {
go addMany(done)
}
for range 4 {
<-done
}
fmt.Println("count:", count)
}
That prints 400,000 every time. My rule: use a channel when work or results move from one goroutine to another, and use a mutex when several goroutines need to read and update one small thing that stays put. If you find yourself writing a goroutine whose only job is to guard a single number, reach for the lock.
A bakery with three bakers
The project is a worker pool, one of the most common shapes in concurrent
programs. A fixed number of workers take jobs from one channel and put results on
another. It’s a bakery: orders come in at the front counter, three bakers bake
them, and main collects the loaves.
Make a new folder and set it up the same way as before:
mkdir bakery
cd bakery
go mod init bakery
Save this as main.go:
package main
import (
"fmt"
"time"
)
const bakers = 3
type Order struct {
id int
bread string
bake time.Duration
}
type Loaf struct {
order Order
baker int
}
func frontCounter(list []Order, orders chan Order) {
for _, order := range list {
orders <- order
}
close(orders)
}
func baker(id int, orders chan Order, loaves chan Loaf) {
for order := range orders {
time.Sleep(order.bake)
loaves <- Loaf{order: order, baker: id}
}
}
func main() {
ms := time.Millisecond
list := []Order{
{1, "sourdough", 400 * ms},
{2, "baguette", 200 * ms},
{3, "rye", 300 * ms},
{4, "brioche", 100 * ms},
{5, "focaccia", 200 * ms},
{6, "pretzel", 100 * ms},
{7, "challah", 300 * ms},
{8, "bagel", 100 * ms},
{9, "ciabatta", 200 * ms},
}
orders := make(chan Order)
loaves := make(chan Loaf)
start := time.Now()
go frontCounter(list, orders)
for id := 1; id <= bakers; id++ {
go baker(id, orders, loaves)
}
made := make([]int, bakers+1)
var alone time.Duration
for range list {
loaf := <-loaves
made[loaf.baker]++
alone += loaf.order.bake
at := time.Since(start).Round(10 * ms)
fmt.Printf("%6v baker %d: order %d, %s\n", at, loaf.baker, loaf.order.id, loaf.order.bread)
}
fmt.Println()
for id := 1; id <= bakers; id++ {
fmt.Printf("baker %d made %d loaves\n", id, made[id])
}
fmt.Println("together:", time.Since(start).Round(10*ms))
fmt.Println("one baker alone:", alone)
}
A time.Duration is a length of time, so 400 * ms is four tenths of a second.
make([]int, bakers+1) makes an array of zeros that can grow (Go calls it a
slice), and fmt.Printf prints with a format, the way printf does in many
languages.
Run it with go run ., and you’ll see something like this:
200ms baker 1: order 2, baguette
300ms baker 1: order 4, brioche
300ms baker 2: order 3, rye
400ms baker 2: order 6, pretzel
400ms baker 3: order 1, sourdough
500ms baker 1: order 5, focaccia
500ms baker 3: order 8, bagel
700ms baker 2: order 7, challah
700ms baker 1: order 9, ciabatta
baker 1 made 4 loaves
baker 2 made 3 loaves
baker 3 made 2 loaves
together: 700ms
one baker alone: 1.9s
Your bakers will split the work a little differently from mine. Nobody assigned order 4 to baker 1. Baker 1 finished the baguette first, so
baker 1 was the one waiting at the orders channel when the brioche came through.
The fast bakers take more orders. Three bakers finished almost two seconds
of baking in seven tenths of one.
Now look at what’s shared. The bakers share nothing but two channels. The tally in
made belongs to main alone, so no lock is needed and no race is possible. The
front counter closes orders when the list runs out, and that’s how every baker’s
for ... range orders loop knows to stop.
Why does the front counter get a goroutine of its own, instead of main sending
the orders itself? Try it and see. The answer is the deadlock from earlier, in a
slightly bigger kitchen.
The project file is in this series’ repository as
projects/go/main.go, and the copy there ends with more
things to try.
What I left out
You haven’t seen sync.WaitGroup, which waits for a group
of goroutines to finish without counting replies, or the context package, which
tells a whole tree of goroutines to stop. Stopping work cleanly is its own big
idea, and it’s the subject of the Kotlin article. I also skipped
channel types that can only send or only receive, the patterns built from chains
of channels, and nearly everything about Go that isn’t concurrency: interfaces,
packages, error handling, testing.
When you want more, Go’s own material is excellent. The concurrency section of A Tour of Go lets you run every example in your browser. Effective Go explains the style behind the motto, and the Go blog’s pipelines article builds bigger shapes out of the pieces you have now.
Look inside a channel
The go command came with a manual, and the source code of Go itself. Ask it how
time.After works:
go doc -src time.After
The function is three lines long, and it hands back a channel. Then run go env GOROOT to find
where Go lives on your disk, and open src/runtime/chan.go inside it. Search for
type hchan struct. That’s what a channel is made of. Bring one question: why is
there a lock in there?
Related
- Kotlin for structured concurrency, where every task you start is also sure to finish.
- Rust for errors as values and for ownership, which stops data races before the program runs.
Tested with Go 1.27.4 and lux 0.21.2, November 2026.