Go's approach to concurrency rests on a simple idea: instead of having goroutines share a variable and coordinate access with locks, let them communicate by passing values through a channel. The Go team phrases this as "don't communicate by sharing memory; share memory by communicating." A channel is a typed conduit through which goroutines send and receive values, with synchronization built in.
Creating a channel
A channel is a first-class value in Go. You declare its type with the chan keyword followed by the element type, and you create it with make:
ch := make(chan string)This creates an unbuffered channel of strings. You can only send and receive values of the declared type. A chan string will not accept an int, and the compiler enforces this.
Channels are reference types, like slices and maps. The variable ch holds a pointer to the channel's internal data structure. Passing a channel to a function doesn't copy the channel, so both sides operate on the same conduit.
Sending and receiving
The <- operator is used for both sending and receiving. The direction of the arrow tells you which operation is happening:
package mainimport "fmt"func main() { ch := make(chan string) go func() { ch <- "hello" // send: value goes into the channel }() msg := <-ch // receive: value comes out of the channel fmt.Println(msg)}The arrow always points in the direction of data flow: ch <- value sends value into ch, and <-ch takes a value out of ch. Reading from a channel (<-ch) can appear on the right-hand side of an assignment or on its own when you want to discard the value.
Blocking behavior
Channels also synchronize the goroutines that use them. Sending and receiving on an unbuffered channel are blocking operations:
- A send blocks until another goroutine is ready to receive.
- A receive blocks until another goroutine is ready to send.
That's why the example above works: the main goroutine blocks at <-ch until the spawned goroutine executes ch <- "hello". Neither side makes progress until both are ready, which is sometimes called a rendezvous.
package mainimport ( "fmt" "time")func worker(ch chan string) { time.Sleep(500 * time.Millisecond) ch <- "work done"}func main() { ch := make(chan string) go worker(ch) fmt.Println("waiting...") result := <-ch // blocks here until worker sends fmt.Println(result)}The main goroutine prints "waiting..." immediately, then blocks. Half a second later, the worker sends its result and the receive unblocks, all without a mutex or a time.Sleep in main.
Unidirectional channels
A channel created with make(chan T) is bidirectional: any goroutine with a reference to it can send or receive. In practice, most channels are used in one direction only: one goroutine sends, another receives. Go lets you express this intent with directional channel types:
| Type | Direction | Description |
|---|---|---|
chan T | bidirectional | can send and receive |
chan<- T | send-only | can only send |
<-chan T | receive-only | can only receive |
Unidirectional channels are most useful as function parameter types. They document intent and let the compiler prevent misuse:
package mainimport "fmt"// producer can only send on resultsfunc producer(results chan<- int) { for i := 0; i < 5; i++ { results <- i } close(results)}// consumer can only receive from resultsfunc consumer(results <-chan int) { for v := range results { fmt.Println(v) }}func main() { ch := make(chan int) go producer(ch) // chan int → chan<- int: implicit conversion consumer(ch) // chan int → <-chan int: implicit conversion}The conversion from a bidirectional channel to a unidirectional one is implicit, so you don't need a cast. The reverse is not allowed: you cannot convert a chan<- int back to a chan int. Trying to receive from a chan<- int or send to a <-chan int is a compile error.
Closing a channel
When a sender is done, it can signal this by closing the channel:
close(ch)Closing a channel has two effects. First, any goroutine that was blocked waiting to receive from the channel is unblocked immediately and receives the zero value of the channel's element type. Second, all subsequent receives also return the zero value.
To distinguish "received a real zero value" from "channel was closed and drained", the receive expression supports a two-value form:
v, ok := <-chok is true if a real value was received, and false if the channel is closed and empty. This mirrors the two-value map lookup pattern.
package mainimport "fmt"func main() { ch := make(chan int, 3) ch <- 10 ch <- 20 close(ch) for { v, ok := <-ch if !ok { fmt.Println("channel closed") break } fmt.Println("received:", v) }}Ranging over a channel
The manual v, ok := <-ch loop is verbose. A for range loop does the same job, reading values until the channel is closed:
package mainimport "fmt"func generate(ch chan<- int, n int) { for i := 0; i < n; i++ { ch <- i } close(ch)}func main() { ch := make(chan int) go generate(ch, 5) for v := range ch { fmt.Println(v) } fmt.Println("done")}Unlike ranging over a map (which yields key and value), ranging over a channel yields a single value per iteration. The loop exits automatically when the channel is closed and drained. If the channel is never closed, for range blocks forever and you get a deadlock.
Closing a channel also works as a broadcast: it unblocks every goroutine that is waiting to receive, all at once. That makes it useful as a "done" signal in fan-out patterns:
done := make(chan struct{})// launch N workers, each receiving from donefor i := 0; i < 3; i++ { go func() { <-done // blocks until done is closed fmt.Println("shutting down") }()}close(done) // unblocks all three goroutines at oncechan struct{} is the idiomatic type for signal-only channels. A struct with no fields occupies zero bytes and tells the reader that only the event matters, not the value.
Buffered channels
All the examples so far used unbuffered channels, where every send must be paired with a simultaneous receive. Go also supports buffered channels, created by passing a capacity to make:
ch := make(chan string, 3) // buffered channel with capacity 3A buffered channel has an internal queue. Sends don't block as long as the buffer isn't full; receives don't block as long as the buffer isn't empty:
package mainimport "fmt"func main() { ch := make(chan int, 3) ch <- 1 // does not block — buffer has space ch <- 2 // does not block ch <- 3 // does not block // ch <- 4 would block — buffer is full fmt.Println(<-ch) // 1 fmt.Println(<-ch) // 2 fmt.Println(<-ch) // 3}Buffered channels decouple the sender from the receiver: the sender can produce a burst of values without waiting for the receiver to process each one. You can use them to bound the number of goroutines in flight, absorb spikes in a pipeline, or build simple work queues.
Nil channels
The zero value of a channel is nil. A nil channel has well-defined, if surprising, behavior:
- Sending to a nil channel blocks forever.
- Receiving from a nil channel blocks forever.
- Closing a nil channel panics.
var ch chan int // nilch <- 1 // blocks forever (deadlock if no other goroutines)<-ch // blocks foreverclose(ch) // panic: close of nil channelBlocking forever sounds useless, but select statements rely on it on purpose. A select case on a nil channel is never selected, which gives you a way to disable a case at runtime:
var ticker <-chan time.Time // nil — case is never selectedif enableTicker { ticker = time.After(1 * time.Second)}select {case <-ticker: // only runs if ticker was setcase result := <-work: process(result)}Setting a channel variable to nil removes that case from a select without restructuring the code.
Channel ownership
Once channels get passed between goroutines, you need clear ownership rules. The pattern that prevents the most bugs is:
- The goroutine that creates a channel is responsible for writing to it and closing it when done.
- Readers should handle the possibility that the channel will be closed.
package mainimport "fmt"// owner creates, writes to, and closes the channelfunc owner() <-chan int { ch := make(chan int) go func() { defer close(ch) for i := 0; i < 5; i++ { ch <- i } }() return ch // returns read-only view to the caller}func main() { // consumer only has a receive-only reference for v := range owner() { fmt.Println(v) }}By returning a <-chan int instead of chan int, owner prevents the caller from accidentally sending to or closing the channel. The close stays inside owner, and defer makes sure it happens. The consumer only needs to read and handle the channel closing, which for range does automatically.
Most channel-based pipelines in Go are built on this pattern: the owner creates and closes, and the consumer reads and reacts to the close.
What this means in practice
Channels are Go's main way for goroutines to communicate safely. They replace shared variables with explicit message passing, so coordinating goroutines becomes a matter of deciding where data flows.
Unbuffered channels synchronize sender and receiver at every exchange. Use them when the timing matters, such as when one goroutine hands off work to another and needs to know it was received. Buffered channels decouple the timing, so use them when you need throughput and the receiver can lag behind for a while.
Keep ownership clear: one goroutine writes and closes, the others only read. That rule prevents the most common channel bugs: panics from a double close, deadlocks from channels nobody closes, and panics from a send on a channel that another goroutine already closed.