SyntaxPilot
Courses/Go Programming/Lesson 47
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 47 of 89

Channels: the basics

channel typemake(chan T)send and receive operatorsunbuffered channels as synchronisationbuffered channels and capacitylen and cap of channelscloserange over a channelcomma-ok receivedirectional channel types (chan<-, <-chan)channels as first-class values

These are the notes for Go episode 47. Raju's cook must hand dishes to the delivery boy. With what you know so far, the cook puts dishes on a shared slice guarded by a mutex, and the boy checks it in a loop: correct, but it checks millions of times (busy waiting). You invent the fix, a serving hatch: Go's channel. You learn to make one, send and receive, how an unbuffered channel makes two goroutines meet, how a buffered channel lets the sender run ahead (len, cap), how the sender says "no more" with close so the receiver can range, the comma-ok receive, send-only and receive-only channel types, and channels as values you can store and send.

All outputs and errors here are from real runs (Go 1.25.1, linux/amd64, a machine with 2 CPUs). Counts and the order of some lines can change between runs.

Facts and sources

  • The Go Memory Model (episode 46): "A send on a channel is synchronized before the completion of the corresponding receive from that channel." "A receive from an unbuffered channel is synchronized before the completion of the corresponding send on that channel." "The closing of a channel is synchronized before a receive that returns a zero value because the channel is closed." "The kth receive from a channel with capacity C is synchronized before the completion of the k+Cth send from that channel."
  • The Go proverb from episode 43: "Don't communicate by sharing memory; share memory by communicating."
  • Compiler and runtime messages below are copied from real runs with Go 1.25.1.

The problem: passing dishes with a shared slice

In Raju's kitchen In Go
the cook finishes a dish every 100 ms a producer goroutine (makes values)
the delivery boy picks them up a consumer goroutine (uses values)
a shelf with a lock a shared slice + sync.Mutex (episode 45)
the boy keeps checking the shelf busy waiting
package main

import (
    "fmt"
    "sync"
    "time"
)

var mu sync.Mutex
var shelf []string // the counter between kitchen and delivery

func main() {
    go func() { // the cook
        for _, dish := range []string{"dosa", "idli", "vada"} {
            time.Sleep(100 * time.Millisecond) // cooking
            mu.Lock()
            shelf = append(shelf, dish)
            mu.Unlock()
        }
    }()
    checks, got := 0, 0
    for got < 3 { // the delivery boy keeps checking the shelf
        checks++
        mu.Lock()
        if len(shelf) > 0 {
            fmt.Println("picked up", shelf[0])
            shelf = shelf[1:]
            got++
        }
        mu.Unlock()
    }
    fmt.Println("checked the shelf", checks, "times")
}

Real output (two runs):

picked up dosa
picked up idli
picked up vada
checked the shelf 19201362 times
checked the shelf 18363394 times

Busy waiting means spinning in a loop on a CPU, doing no useful work, only to notice that something changed. About 19 million checks in 300 ms, almost all empty. Why it fails: a mutex protects data, but it cannot say "something arrived, wake up".

The fix: a channel

A channel is a typed pipe between goroutines: one goroutine puts values in, another takes them out, and a goroutine that has to wait sleeps (uses no CPU) until it can continue.

Serving hatch Go Syntax
a hatch that only fits dishes a channel of strings: type chan string hatch := make(chan string)
the cook pushes a dish in send hatch <- dish
the boy takes one out, waiting if needed receive dish := <-hatch (or just <-hatch to discard)
  • The channel type is chan + the element type: chan int, chan string, chan Order.
  • Like maps and slices (episodes 13, 15), you create channels with make. A channel declared but not made is nil (episode 48 shows what that does).
  • <- is the channel operator: in ch <- v the arrow points into the channel (send); in <-ch it points out (receive).
package main

import (
    "fmt"
    "time"
)

func main() {
    hatch := make(chan string) // a serving hatch for dishes
    go func() { // the cook
        for _, dish := range []string{"dosa", "idli", "vada"} {
            time.Sleep(100 * time.Millisecond) // cooking
            hatch <- dish // send: hand the dish through
        }
    }()
    for i := 0; i < 3; i++ {
        dish := <-hatch // receive: waits until a dish arrives
        fmt.Println("picked up", dish)
    }
}

Real output:

picked up dosa
picked up idli
picked up vada

No slice, no mutex, no counting loop: the boy sleeps between dishes, and the scheduler (episode 44) wakes him when a value arrives. The channel carries both the data and the signal.

Unbuffered channels: hand to hand

make(chan T) with no size makes an unbuffered channel: it holds no values. A value goes straight from sender to receiver:

  • a send blocks until a receiver takes the value;
  • a receive blocks until a sender offers one.

So the handover is a meeting point (also called a rendezvous): when it completes, both goroutines know it happened. It is a synchronising operation (episode 46): everything the sender did before the send happens before everything the receiver does after the receive.

package main

import (
    "fmt"
    "time"
)

func main() {
    start := time.Now()
    at := func() time.Duration {
        return time.Since(start).Round(100 * time.Millisecond)
    }
    hatch := make(chan string) // unbuffered: no space at all
    go func() {
        fmt.Println(at(), "cook: dosa ready, waiting at the hatch")
        hatch <- "dosa" // blocks until someone takes it
        fmt.Println(at(), "cook: handed over, back to the stove")
    }()
    time.Sleep(300 * time.Millisecond) // the delivery boy is late
    fmt.Println(at(), "boy: here now")
    fmt.Println(at(), "boy: got", <-hatch)
    time.Sleep(50 * time.Millisecond)
}

Real output:

0s cook: dosa ready, waiting at the hatch
300ms boy: here now
300ms boy: got dosa
300ms cook: handed over, back to the stove

The send waited 300 ms for its partner. (The last two lines can swap: after the handover both goroutines run on.) The final Sleep gives the cook a moment to print before main returns.

Sending with nobody on the other side

package main

import "fmt"

func main() {
    hatch := make(chan string)
    hatch <- "dosa" // nobody is on the other side
    fmt.Println("sent")
}

Real output:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    main.go:7 +0x28
exit status 2

[chan send] is the state goroutine 1 is stuck in. A send on an unbuffered channel needs another goroutine ready to receive.

Buffered channels: a shelf in the hatch

make(chan T, n) makes a buffered channel with capacity n: a queue of up to n values.

  • A send blocks only when the buffer is full; a receive blocks only when it is empty.
  • Values come out first in, first out (FIFO), in the order they were sent.
  • len(ch) = how many values are waiting now; cap(ch) = the capacity.
package main

import "fmt"

func main() {
    shelf := make(chan string, 3) // buffered: a shelf with 3 slots
    shelf <- "dosa"
    shelf <- "idli"
    fmt.Println("on the shelf:", len(shelf), "of", cap(shelf))
    shelf <- "vada" // still fits: no receiver needed yet
    fmt.Println("on the shelf:", len(shelf), "of", cap(shelf))
    fmt.Println("took", <-shelf)
    fmt.Println("on the shelf:", len(shelf), "of", cap(shelf))
    shelf <- "poha"
    shelf <- "upma" // a 4th dish on a full shelf...
    fmt.Println("never printed")
}

Real output:

on the shelf: 2 of 3
on the shelf: 3 of 3
took dosa
on the shelf: 2 of 3
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    main.go:15 +0x3b6
exit status 2

Points to remember: - A buffer lets the sender run ahead by up to cap values; it does not remove the need for a receiver. - Don't use a big buffer to hide a deadlock or a slow consumer: it only delays the problem. - Don't make decisions from len(ch): by the time you act, another goroutine may have changed it. It is fine for logging and monitoring. - With a buffered channel, the k-th receive happens before the (k+C)-th send completes, so a buffered channel of capacity C can limit how many goroutines run at once (a semaphore, episode 52).

Unbuffered make(chan T) Buffered make(chan T, n)
cap(ch) 0 n
send blocks when no receiver is ready the buffer is full
receive blocks when no sender is ready the buffer is empty
synchronises sender and receiver meet only when the buffer is full/empty

close and range

The receiver often doesn't know how many values will come. The sender says "no more values will ever be sent" with close(ch). A for v := range ch loop receives values until the channel is closed and empty.

Without close

package main

import "fmt"

func main() {
    hatch := make(chan string, 2)
    go func() { // the cook makes two dishes and goes home
        hatch <- "dosa"
        hatch <- "idli"
    }()
    for dish := range hatch { // keep taking dishes...
        fmt.Println("delivering", dish)
    }
    fmt.Println("all delivered")
}

Real output:

delivering dosa
delivering idli
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    main.go:11 +0xe7
exit status 2

The loop waits for a third dish forever ([chan receive]).

With close, and the comma-ok receive

package main

import "fmt"

func cook(dishes []string, hatch chan string) {
    for _, d := range dishes {
        hatch <- d
    }
    close(hatch) // "kitchen closed: no more dishes"
}

func main() {
    hatch := make(chan string, 2)
    go cook([]string{"dosa", "idli", "vada", "poha"}, hatch)
    for dish := range hatch { // stops when closed and empty
        fmt.Println("delivering", dish)
    }
    fmt.Println("all delivered")

    dish, ok := <-hatch // comma-ok: was this a real dish?
    fmt.Printf("after close: %q, ok=%v\n", dish, ok)
}

Real output:

delivering dosa
delivering idli
delivering vada
delivering poha
all delivered
after close: "", ok=false
  • close does not throw away buffered values: range drains them, then stops.
  • A receive from a closed, empty channel never blocks: it returns the element type's zero value at once ("" for strings, 0 for ints).
  • The comma-ok receive v, ok := <-ch tells the two apart: ok == true for a value that was really sent, ok == false only when the channel is closed and empty. (The same "comma-ok" idea as map lookups, episode 15, and type assertions, episode 22.)
  • Only the sender closes, and only when it is sure no more sends will happen. Closing is a message ("no more values"), not a cleanup: a channel nobody closes is garbage-collected like any other value when it is no longer used.
  • What happens when you send on a closed channel, or close one twice, is episode 48.

Directional channel types

Type Meaning Allowed
chan T bidirectional send, receive, close
chan<- T send-only send, close
<-chan T receive-only receive (and range)

Read the arrow as the direction values flow. A bidirectional channel converts automatically to either direction when you pass it to a function parameter of that type; the compiler then enforces it.

package main

import "fmt"

// the cook may only send into the hatch
func cook(out chan<- string) {
    out <- "dosa"
    fmt.Println(<-out) // a cook taking dishes back out?
    close(out)
}

// the delivery boy may only receive from it
func deliver(in <-chan string) {
    for d := range in {
        fmt.Println("delivering", d)
    }
}

func main() {
    hatch := make(chan string, 1) // a two-way channel...
    go cook(hatch)                // ...becomes send-only here
    deliver(hatch)                // ...and receive-only here
}

Real compiler error:

# command-line-arguments
./main.go:8:19: invalid operation: cannot receive from send-only channel chan<- string out (variable of type chan<- string)

Fixed (the line replaced with out <- "idli"), real output:

delivering dosa
delivering idli

Directional types document who sends and who receives, and turn a misuse into a compile-time error (found before the program runs). Closing a receive-only channel is also a compile error: only the sending side may close.

Channels as first-class values

A first-class value can be used anywhere a value can: stored in variables, structs, slices and maps, passed to and returned from functions, and even sent through channels. Channels are first-class.

package main

import "fmt"

// an order carries its own reply channel
type Order struct {
    Dish  string
    Reply chan string
}

func kitchen(orders <-chan Order) {
    for o := range orders {
        o.Reply <- o.Dish + " is ready"
    }
}

func main() {
    orders := make(chan Order)
    go kitchen(orders)

    tables := map[string]chan string{} // channels stored in a map
    for _, t := range []string{"table 1", "table 2"} {
        tables[t] = make(chan string, 1)
    }
    orders <- Order{"dosa", tables["table 1"]}
    orders <- Order{"idli", tables["table 2"]}
    fmt.Println("table 1:", <-tables["table 1"])
    fmt.Println("table 2:", <-tables["table 2"])
    close(orders)

    var none chan string // zero value of a channel type
    fmt.Printf("zero value: %v, type: %T\n", none, none)
}

Real output:

table 1: dosa is ready
table 2: idli is ready
zero value: <nil>, type: chan string
  • A struct field holding a channel (Reply) is the request/reply pattern: the server answers on the channel the request brought with it.
  • A channel value is a reference to the channel's internal data: copying it (passing it to kitchen, storing it in a map) gives another handle to the same channel, like maps (episode 15).
  • The zero value of a channel type is nil; %T prints its type (episode 18).
  • Two channel values are == when they refer to the same channel (made by the same make).

Mini project: order pipeline

Two stages connected by channels: takeOrders → orders (buffered) → cook → ready → main.

package main

import (
    "fmt"
    "time"
)

// stage 1: takes 8 orders, then closes its output
func takeOrders(out chan<- string) {
    for _, d := range []string{"dosa", "idli", "vada", "poha", "upma", "dosa", "idli", "chai"} {
        out <- d
    }
    close(out)
}

// stage 2: cooks each order and passes it on
func cook(in <-chan string, out chan<- string, queued func() int) {
    for d := range in {
        time.Sleep(20 * time.Millisecond) // a slow cook
        out <- fmt.Sprintf("%s ready (waiting orders: %d)", d, queued())
    }
    close(out)
}

func main() {
    orders := make(chan string, 5)
    ready := make(chan string)
    go takeOrders(orders)
    go cook(orders, ready, func() int { return len(orders) })
    for dish := range ready {
        fmt.Println(dish)
    }
}

Real output:

dosa ready (waiting orders: 5)
idli ready (waiting orders: 5)
vada ready (waiting orders: 5)
poha ready (waiting orders: 4)
upma ready (waiting orders: 3)
dosa ready (waiting orders: 2)
idli ready (waiting orders: 1)
chai ready (waiting orders: 0)

The order-taker fills the 5-slot buffer and waits; as the slow cook works through it, the queue drains. Each stage closes the channel it sends on, so every range ends and the program finishes cleanly. (len(orders) is used only for printing, which is the safe use of len.)

Common mistakes (and the real messages)

Mistake Real message / result Why Fix
busy-waiting on a shared slice checked the shelf 19201362 times a lock can't signal "arrived" a channel
send on an unbuffered channel, no receiver fatal error: all goroutines are asleep - deadlock! / goroutine 1 [chan send] a send needs a partner receive in another goroutine
send on a full buffer deadlock! / [chan send] capacity used up a consumer that keeps up
range over a channel nobody closes deadlock! / [chan receive] the loop waits forever the sender calls close
receiver closes the channel (next episode: the sender panics) only the sender knows it's done the sender closes
receive from a send-only channel invalid operation: cannot receive from send-only channel chan<- string out (variable of type chan<- string) wrong direction use <-chan T
deciding from len(ch) flaky logic it can change at once just send/receive
a huge buffer "to fix" a deadlock the deadlock comes later the receiver still can't keep up fix the design
treating a zero value as data after close "" processed as a dish closed channels return zero values range or comma-ok

Practice

  1. What does this print?
ch := make(chan int, 1)
ch <- 10
fmt.Println(len(ch), cap(ch))
fmt.Println(<-ch)
fmt.Println(len(ch), cap(ch))
  1. Write func counter(n int) <-chan int that returns a channel delivering 1..n and then closes it. Print its values with range.
  2. Why does the shelf-and-mutex program use a full CPU while waiting, but the channel version doesn't?
  3. Change the timestamp program's channel to make(chan string, 1). What changes in the output, and why?
Solution 1
1 1
10
0 1
Solution 2
package main

import "fmt"

func counter(n int) <-chan int {
    ch := make(chan int)
    go func() {
        for i := 1; i <= n; i++ {
            ch <- i
        }
        close(ch)
    }()
    return ch // a bidirectional channel returned as receive-only
}

func main() {
    for v := range counter(5) {
        fmt.Print(v, " ")
    }
    fmt.Println()
}

Real output: 1 2 3 4 5. The function owns the channel: it makes it, sends, and closes it; callers can only receive. This is the generator pattern (episode 52).

Solution 3

The mutex version's loop never blocks: it locks, looks, unlocks and repeats. A receive on an empty channel parks the goroutine; the scheduler doesn't run it again until a sender makes a value available.

Solution 4

Real output with capacity 1:

0s cook: dosa ready, waiting at the hatch
0s cook: handed over, back to the stove
300ms boy: here now
300ms boy: got dosa

The dosa fits in the 1-slot buffer, so the send doesn't wait for the boy: the cook is back at the stove at 0 s. With a buffer, the sender and receiver no longer meet.

Quick quiz

1. A channel of capacity 2: send 1 and 2, close, range printing each value, then v, ok := <-ch; fmt.Println(v, ok). Output? (From the video.)

A. 1 2 0 false · B. 1 2 then deadlock · C. panic: send on closed channel · D. 1 2 2 true

Answer

A. close keeps buffered values; range drains 1 and 2 and stops; the last receive returns the zero value 0 and ok == false.

2. On an unbuffered channel, when does a send complete?

Answer

When a receiver takes the value: sender and receiver meet.

3. What do len and cap mean for a channel?

Answer

len: values waiting in the buffer now. cap: the buffer size (0 for unbuffered).

4. Can a function with a <-chan int parameter close it?

Answer

No: closing a receive-only channel is a compile error. Only the sending side closes.

Interview questions

  1. What is a channel? A typed conduit between goroutines; sends and receives block as needed, so it carries data and synchronisation together.
  2. Unbuffered vs buffered? Unbuffered (cap 0): send and receive meet (rendezvous). Buffered (cap n): a FIFO queue; send blocks only when full, receive only when empty.
  3. When should you close a channel, and who closes it? When no more values will be sent and receivers need to know (e.g. to end a range). The sender (owner) closes; never the receiver.
  4. What does receiving from a closed channel return? Remaining buffered values first, then the zero value immediately with ok == false.
  5. What are directional channels for? chan<- T and <-chan T restrict a function to sending or receiving, documenting intent and making misuse a compile error.
  6. Is a channel a reference type? A channel value refers to shared internal state; copies refer to the same channel. Its zero value is nil.
  7. Channels or mutexes? Channels to pass ownership of data or signal events between goroutines; mutexes to protect shared state accessed in place. (Decision guide in episode 54.)
  8. What does "share memory by communicating" mean? Instead of several goroutines touching shared variables under locks, send the data to the goroutine that should own it.
  9. What does fatal error: all goroutines are asleep - deadlock! with [chan send] mean? Every goroutine is blocked; goroutine 1 is stuck sending on a channel nobody will receive from.

Glossary

Term Meaning Example
Producer a goroutine that makes values for others the cook
Consumer a goroutine that uses values others made the delivery boy
Busy waiting spinning in a loop on a CPU just to notice a change checked the shelf 19201362 times
Channel a typed pipe for sending values between goroutines hatch := make(chan string)
Channel type chan + element type chan int
Element type the type of values a channel carries string in chan string
make(chan T) creates an unbuffered channel make(chan string)
make(chan T, n) creates a buffered channel with capacity n make(chan string, 3)
Channel operator <- sends (ch <- v) or receives (<-ch) dish := <-hatch
Send put a value into a channel hatch <- "dosa"
Receive take a value out of a channel <-hatch
Block wait (sleeping, no CPU) until the operation can proceed a receive on an empty channel
Unbuffered channel a channel with no storage: sender and receiver meet cap(ch) == 0
Rendezvous a meeting point of two goroutines an unbuffered handover
Synchronising operation an operation that orders memory between goroutines channel send → receive
Buffered channel a channel with a FIFO queue of fixed size make(chan string, 3)
Capacity the size of a channel's buffer cap(shelf) = 3
len(ch) values currently waiting in a channel 2 of 3
FIFO first in, first out dosa sent first, received first
Deadlock every goroutine is blocked forever [chan send], [chan receive]
close(ch) marks a channel: no more values will be sent close(hatch)
for v := range ch receives until the channel is closed and empty for dish := range hatch
Zero value the default value of a type "", 0, nil
Comma-ok receive v, ok := <-ch; ok false when closed and empty "", ok=false
Bidirectional channel can send and receive chan string
Send-only channel can only send (and close) chan<- string
Receive-only channel can only receive <-chan string
Compile-time error an error found by the compiler before the program runs cannot receive from send-only channel
First-class value a value usable anywhere: variables, fields, maps, arguments, results, messages a channel in a struct
Request/reply a request that carries the channel to answer on Order{Dish, Reply}
Reference (to a channel) a channel value points to shared internal state; copies share it passing orders to kitchen
Pipeline stages connected by channels takeOrders → cook → main
Generator a function that returns a channel it fills and closes counter(5)

Summary

  • A shared slice + mutex means busy waiting; a channel lets the receiver sleep until data arrives.
  • ch := make(chan T) (unbuffered) or make(chan T, n) (buffered); send ch <- v, receive v := <-ch.
  • Unbuffered: send and receive meet; it's a synchronising operation. A send with no receiver → deadlock! [chan send].
  • Buffered: FIFO queue; send blocks when full, receive when empty; len = waiting, cap = size.
  • The sender closes; for v := range ch drains and stops; v, ok := <-ch gives ok == false once closed and empty; closed channels return zero values.
  • chan<- T send-only, <-chan T receive-only, checked by the compiler.
  • Channels are first-class values: in structs, maps, arguments, even sent over channels; zero value nil.

Next episode: Channels: semantics in depth: nil channels, send on a closed channel, closing twice, who should close, deadlocks, signalling with chan struct{}, closing as broadcast, and the runtime's hchan (buffer, sendq, recvq).