0PricingLogin
Go Academy · Lesson

Unbuffered Channels

Synchronous handoff between goroutines

What Is a Channel?

A channel is a typed conduit for communicating between goroutines. Channels follow Go's mantra: Do not communicate by sharing memory; share memory by communicating.

package main
import "fmt"

func main() {
    ch := make(chan int)   // unbuffered int channel

    go func() {
        ch <- 42  // send: blocks until someone receives
    }()

    v := <-ch  // receive: blocks until someone sends
    fmt.Println(v) // 42
}

Unbuffered Channel Semantics

An unbuffered channel has no capacity. A send blocks until a receiver is ready, and a receive blocks until a sender sends. This provides a guaranteed synchronous handoff:

package main
import "fmt"

func double(in <-chan int, out chan<- int) {
    for v := range in {
        out <- v * 2
    }
    close(out)
}

func main() {
    in := make(chan int)
    out := make(chan int)
    go double(in, out)
    go func() { in <- 3; in <- 5; close(in) }()
    for v := range out { fmt.Println(v) }
    // 6
    // 10
}

All lessons in this course

  1. Launching Goroutines
  2. Unbuffered Channels
  3. Buffered Channels
  4. Channel Direction and Pipeline Patterns
← Back to Go Academy