Level: BeginnerGo Programs

Go Channel Programs with Output: Buffered, select and Pipelines

Updated 18 min read
Go Channel Programs featured image: channel, select and pipeline output

Go channel programs let goroutines send values to each other safely, without shared variables or locks. Go’s motto is “do not communicate by sharing memory; share memory by communicating”, and channels are how you do it. In this post, you will write fourteen channel programs with their exact output and the logic explained in comments, including producer-consumer, ping-pong, pipelines and timeouts with select.

You should first read our Go goroutine programs, because every channel connects goroutines. For the theory, see Go channels explained with examples and the Go select statement. All programs were tested on Go 1.27.

What are Go Channel Programs?

Go channel programs use a channel, which is a typed pipe between goroutines. One goroutine sends with ch <- value, and another receives with value := <-ch. An unbuffered channel makes the sender and receiver meet at the same moment, while a buffered channel has room for a few values.

Think of a channel as a pass-through window between a kitchen and a dining room. The cook puts a plate in the window, and the waiter takes it out. With no shelf (unbuffered), the cook waits until the waiter takes the plate. With a shelf for three plates (buffered), the cook can put up to three plates before waiting.

Why Go Channel Programs Matter

Channels are the main way goroutines work together. For example, a web scraper sends pages to a parser, a job queue sends tasks to workers and a server uses a channel to signal shutdown. So Go channel programs are one of the most tested areas in Go interviews.

  • Hand-off: pass work and results between goroutines.
  • Signals: tell goroutines to stop by closing a channel.
  • Timeouts: give up on slow work with select and time.After.
  • Interviews: deadlocks, closed channels and producer-consumer are classic questions.

How Go Channel Programs Work

A send blocks until there is space or a receiver. A receive blocks until a value arrives or the channel is closed. When the sender is finished, it closes the channel, and a for range loop on the receiver side stops after the last value.

Go channel programs diagram showing a producer sending values through a channel to a consumer
The producer sends values into the channel, the consumer receives them in order, and close tells the consumer that no more values are coming.

The table below sums up channel operations.

OperationSyntaxBehaviour
Create unbufferedmake(chan int)Send waits for a receiver
Create bufferedmake(chan int, 3)Send waits only when full
Sendch <- vPanics if channel is closed
Receivev := <-chGets zero value after close
Receive with okv, ok := <-chok is false after close and empty
Closeclose(ch)Only the sender should close
Rangefor v := range chStops after close
Send-only typechan<- intFunction can only send
Receive-only type<-chan intFunction can only receive

Basic Go Channel Programs

These first Go channel programs show sending, receiving and closing. Read the comments in each program, because they explain every new piece of syntax.

Program 1: Send and Receive with an Unbuffered Channel

package main

import "fmt"

func main() {
    // make creates a new channel that carries string values.
    // It is unbuffered, so the sender and the receiver must meet.
    message := make(chan string)

    // "go" runs this small function in a new goroutine.
    go func() {
        message <- "order #501 packed" // <- sends a value into the channel
    }()

    // <-message waits here until the goroutine sends a value.
    received := <-message
    fmt.Println(received)
}
order #501 packed

Here is how it works. First, make creates the channel. Then the goroutine sends a string, and main waits on <-message until that string arrives. So the program never exits before the goroutine has done its job.

Program 2: Buffered Channel with len and cap

package main

import "fmt"

func main() {
    // The second argument 3 gives the channel room for 3 values.
    queue := make(chan string, 3)

    // No goroutine is needed here: a send only waits when the buffer is full.
    queue <- "Asha"
    queue <- "Ravi"

    // len is how many values are waiting, cap is the total room.
    fmt.Println("len:", len(queue), "cap:", cap(queue))

    fmt.Println(<-queue) // values come out first in, first out
    fmt.Println(<-queue)
    fmt.Println("len now:", len(queue))
}
len: 2 cap: 3
Asha
Ravi
len now: 0

A buffered channel works like a small queue. You put two names in, so len is 2 while cap stays 3. Then you take them out in the same order they went in.

Program 3: Wait for a Goroutine to Finish

package main

import "fmt"

// cookFood does some work and then sends true to say it has finished.
func cookFood(done chan bool) {
    fmt.Println("cooking rice...")
    fmt.Println("rice is ready")
    done <- true // tell main that the work is finished
}

func main() {
    done := make(chan bool) // a channel that carries true or false

    go cookFood(done) // start the work in a new goroutine

    <-done // wait here; we do not need the value itself
    fmt.Println("dinner is served")
}
cooking rice...
rice is ready
dinner is served

This is the simplest way to wait for a goroutine. main starts cookFood and then blocks on <-done. When the goroutine sends true, main wakes up and prints the last line.

Program 4: Range over a Channel and Close

package main

import "fmt"

func main() {
    squares := make(chan int)

    go func() {
        for i := 1; i <= 5; i++ {
            squares <- i * i // send the square of i
        }
        close(squares) // close means: no more values are coming
    }()

    // range keeps receiving until the channel is closed and empty.
    for square := range squares {
        fmt.Print(square, " ")
    }
    fmt.Println("| done")
}
1 4 9 16 25 | done

The goroutine sends five squares and then closes the channel. The range loop in main prints each value as it arrives. Without close, the loop would wait forever after the last value, and Go would report a deadlock.

Program 5: Detect a Closed Channel with ok

package main

import "fmt"

func main() {
    numbers := make(chan int, 2)
    numbers <- 10
    close(numbers)

    // ok is true when a real value was received.
    value, ok := <-numbers // the buffered 10 is still there
    fmt.Println(value, ok)

    value, ok = <-numbers // the channel is closed and empty now
    fmt.Println(value, ok)
}
10 true
0 false

After close, a receiver still gets any values left in the buffer. So the first receive gets 10 and ok is true. Once the channel is empty, you get the zero value 0 and ok is false.

Patterns in Go Channel Programs

These Go channel programs show the patterns you will use in real projects.

Program 6: Producer and Consumer

package main

import (
    "fmt"
    "sync"
)

// producer sends order IDs. chan<- int means it may only send.
func producer(orders chan<- int, count int) {
    for id := 1; id <= count; id++ {
        orders <- id
    }
    close(orders) // the producer owns the channel, so it closes it
}

// consumer receives orders. <-chan int means it may only receive.
// wg is a wait group: it lets main wait until this goroutine is done.
func consumer(orders <-chan int, wg *sync.WaitGroup) {
    defer wg.Done() // defer runs wg.Done() when this function returns
    for id := range orders {
        fmt.Println("shipping order", id)
    }
}

func main() {
    orders := make(chan int, 2)
    var wg sync.WaitGroup
    wg.Add(1)               // we will wait for one goroutine
    go consumer(orders, &wg) // &wg passes a pointer, so both share one wait group
    producer(orders, 4)
    wg.Wait() // wait until the consumer has handled every order
}
shipping order 1
shipping order 2
shipping order 3
shipping order 4

The producer sends four order IDs and closes the channel. The consumer ranges over the same channel and prints each order. Then wg.Wait() keeps main alive until the consumer calls wg.Done(). The arrows in chan<- int and <-chan int also stop each side from doing the wrong job by mistake.

Program 7: Add Up Numbers and Send Back the Total

package main

import "fmt"

// sumNumbers adds every number and sends the total into the result channel.
func sumNumbers(numbers []int, result chan int) {
    total := 0
    for _, number := range numbers { // _ skips the index we do not need
        total += number
    }
    result <- total // send the answer back to main
}

func main() {
    prices := []int{120, 80, 50}
    result := make(chan int)

    go sumNumbers(prices, result) // do the work in a goroutine

    total := <-result // wait for the answer
    fmt.Println("bill total:", total)
}
bill total: 250

This is how a goroutine returns a value. A goroutine cannot use return to give main a result. Instead, it sends the result into a channel, and main receives it.

Program 8: A Generator Function

package main

import "fmt"

// evens returns a receive-only channel that gives even numbers up to limit.
func evens(limit int) <-chan int {
    output := make(chan int)
    go func() {
        defer close(output) // close the channel when the loop ends
        for number := 0; number <= limit; number += 2 {
            output <- number
        }
    }()
    return output // return at once; the goroutine keeps sending
}

func main() {
    for number := range evens(10) {
        fmt.Print(number, " ")
    }
    fmt.Println()
}
0 2 4 6 8 10

The evens function starts a goroutine and returns the channel right away. Then the caller just ranges over it, without knowing a goroutine exists. When the loop inside ends, defer closes the channel and the range in main stops.

Program 9: A Pipeline of Stages

package main

import "fmt"

// generate sends each given number into a new channel.
// numbers ...int means the function accepts any count of ints.
func generate(numbers ...int) <-chan int {
    output := make(chan int)
    go func() {
        for _, number := range numbers {
            output <- number
        }
        close(output)
    }()
    return output
}

// square reads numbers from input and sends their squares on.
func square(input <-chan int) <-chan int {
    output := make(chan int)
    go func() {
        for number := range input { // read from the previous stage
            output <- number * number // send to the next stage
        }
        close(output)
    }()
    return output
}

func main() {
    // Step 1: generate 1, 2, 3.
    // Step 2: square them once (1, 4, 9).
    // Step 3: square them again (1, 16, 81).
    for value := range square(square(generate(1, 2, 3))) {
        fmt.Print(value, " ")
    }
    fmt.Println()
}
1 16 81

Each stage is a goroutine, and channels connect the stages. Values flow through like parts on an assembly line. When one stage closes its output, the next stage’s range ends, so the close travels down the line. See our Go pipeline pattern guide for fan-out and fan-in.

select in Go Channel Programs

In Go channel programs, select waits on several channel operations and runs the first one that is ready.

Program 10: Timeout with select and time.After

package main

import (
    "fmt"
    "time"
)

// slowAPI pretends to call a server that answers after the given delay.
func slowAPI(delay time.Duration) <-chan string {
    reply := make(chan string, 1) // buffered so the goroutine never gets stuck
    go func() {
        time.Sleep(delay)
        reply <- "response"
    }()
    return reply
}

func main() {
    delays := []time.Duration{50 * time.Millisecond, 300 * time.Millisecond}
    for _, delay := range delays {
        // select waits for whichever case is ready first.
        select {
        case answer := <-slowAPI(delay):
            fmt.Println(delay, "->", answer)
        case <-time.After(100 * time.Millisecond): // give up after 100ms
            fmt.Println(delay, "-> timeout")
        }
    }
}
50ms -> response
300ms -> timeout

Whichever channel is ready first wins. The 50ms call answers before the 100ms timer, so you see the response. But the 300ms call is too slow, so the timer wins. A buffer of 1 lets the slow goroutine finish its send later, even though nobody reads it.

Program 11: Non-Blocking Send with default

package main

import "fmt"

func main() {
    alerts := make(chan string, 1) // room for only one alert
    for _, alert := range []string{"CPU high", "disk full", "memory low"} {
        select {
        case alerts <- alert: // works only if there is room
            fmt.Println("queued:", alert)
        default: // runs when the send would block
            fmt.Println("dropped:", alert)
        }
    }
    fmt.Println("in queue:", <-alerts)
}
queued: CPU high
dropped: disk full
dropped: memory low
in queue: CPU high

The first alert fills the only slot. After that, a send would block, so select runs default and drops the alert. This is useful when you would rather drop a message than slow the sender down.

Program 12: Stop a Goroutine with a done Channel

package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan struct{}) // struct{} carries no data; it is just a signal
    ticks := make(chan int)

    go func() {
        defer close(ticks)
        for i := 1; ; i++ { // no end condition: loop until told to stop
            select {
            case <-done: // a closed channel is always ready to receive
                return
            case ticks <- i:
                time.Sleep(10 * time.Millisecond)
            }
        }
    }()

    for tick := range ticks {
        fmt.Println("tick", tick)
        if tick == 3 {
            close(done) // ask the goroutine to stop
            break
        }
    }
    fmt.Println("stopped")
}
tick 1
tick 2
tick 3
stopped

The goroutine keeps sending ticks until done is closed. After tick 3, main closes done and leaves the loop. Closing done wakes every goroutine waiting on it. In real apps, context.Context does the same job, as in our Go context guide.

Most Asked Interview Go Channel Programs

These two Go channel programs are asked in almost every concurrency round.

Program 13: Ping-Pong Between Two Goroutines

package main

import (
    "fmt"
    "sync"
)

// player waits for the ball, hits it, and sends it back with a higher number.
func player(name string, receive <-chan int, send chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    for ball := range receive { // wait for the ball
        fmt.Println(name, "hits", ball)
        if ball == 6 {
            close(send) // game over: this ends the other player's loop
            return
        }
        send <- ball + 1 // send it back
    }
    close(send) // the other side closed, so close ours too
}

func main() {
    ping := make(chan int)
    pong := make(chan int)
    var wg sync.WaitGroup
    wg.Add(2) // wait for two players
    go player("ping", ping, pong, &wg)
    go player("pong", pong, ping, &wg)
    ping <- 1 // serve the first ball
    wg.Wait()
}
ping hits 1
pong hits 2
ping hits 3
pong hits 4
ping hits 5
pong hits 6

The ball passes back and forth on two unbuffered channels, so the order is always the same. Each player reads from one channel and sends on the other. When the ball reaches 6, one player closes its channel, which ends the other player’s loop.

Program 14: Merge Two Channels (Fan-In)

package main

import (
    "fmt"
    "slices"
    "sync"
)

// copyInto moves every value from source into output.
func copyInto(source <-chan string, output chan<- string, wg *sync.WaitGroup) {
    defer wg.Done()
    for value := range source {
        output <- value
    }
}

// closeWhenDone waits for both copiers and then closes output.
func closeWhenDone(output chan string, wg *sync.WaitGroup) {
    wg.Wait()
    close(output)
}

// merge joins two channels into one.
func merge(first, second <-chan string) <-chan string {
    output := make(chan string)
    var wg sync.WaitGroup
    wg.Add(2)
    go copyInto(first, output, &wg)
    go copyInto(second, output, &wg)
    go closeWhenDone(output, &wg) // close only when both are done
    return output
}

// feed sends the given cities into a new channel.
func feed(cities ...string) <-chan string {
    output := make(chan string)
    go func() {
        for _, city := range cities {
            output <- city
        }
        close(output)
    }()
    return output
}

func main() {
    var allCities []string
    for city := range merge(feed("pune", "goa"), feed("delhi")) {
        allCities = append(allCities, city) // append adds to the slice
    }
    slices.Sort(allCities) // arrival order varies, so sort for stable output
    fmt.Println(allCities)
}
[delhi goa pune]

Two goroutines copy values from each input into one shared output channel. A third goroutine waits for both copiers and then closes the output. Because the arrival order can change from run to run, you sort the result before printing it.

Buffered vs Unbuffered Go Channel Programs

Every one of these Go channel programs picks a channel kind. The diagram and table below compare the two.

Go channel programs comparison of unbuffered and buffered channels
An unbuffered channel makes sender and receiver meet, while a buffered channel lets the sender continue until the buffer is full.
FeatureUnbuffered make(chan T)Buffered make(chan T, n)
Send blocksUntil a receiver takes itOnly when the buffer is full
Sync guaranteeSender knows it was receivedSender only knows it was queued
Use in a single goroutineDeadlocksWorks up to n values
Typical useHand-off, turns, signalsQueues, smoothing bursts
MemoryNo storageSpace for n values

So use unbuffered channels when timing matters, and buffered channels when you want a small queue between fast and slow parts.

Common Mistakes in Go Channel Programs

  • Sending with no receiver: an unbuffered send in main alone deadlocks.
  • Forgetting to close: a range loop never ends, and Go reports a deadlock.
  • Closing from the receiver: only the sender should close, or it may panic with “send on closed channel”.
  • Closing twice: this panics, so make one goroutine responsible for closing.
  • Leaking goroutines on timeout: give the result channel a buffer of 1 so the late sender does not block forever.

Best Practices for Go Channel Programs

  • Use directional types like <-chan T in function signatures.
  • Let the producer close, and let consumers use range.
  • Use struct{} for signals, such as done chan struct{}, because it carries no data.
  • Add timeouts with select whenever you wait on something outside your control.
  • Prefer context.Context for cancellation in real services.

Go Channel Programs Interview Questions and Answers

Interviewers ask these Go channel programs more than any other concurrency questions. Each program is complete, with real output from Go 1.27.

Closed Channel Questions

Q1. What happens when you send on a closed channel?

package main

func main() {
    numbers := make(chan int, 1)
    close(numbers)
    numbers <- 1 // sending on a closed channel panics
}
panic: send on closed channel

Go stops the program with a panic. Once a channel is closed, nobody may send on it again.

Q2. Can you close a channel twice?

package main

func main() {
    numbers := make(chan int)
    close(numbers)
    close(numbers) // the second close panics
}
panic: close of closed channel

No, the second close panics. That is why only one goroutine should be in charge of closing.

Q3. What does this program print?

package main

import "fmt"

func main() {
    words := make(chan string)
    close(words)

    word, ok := <-words
    fmt.Printf("%q %v\n", word, ok) // %q prints the string with quotes
    fmt.Printf("%q\n", <-words)     // still returns the zero value
}
"" false
""

Receiving from a closed channel never blocks. It returns the zero value right away, every time. For a string, the zero value is the empty string "".

Blocking and Deadlock Questions

Q4. What does this program print?

package main

import "fmt"

func main() {
    numbers := make(chan int, 2)
    numbers <- 1
    numbers <- 2
    numbers <- 3 // buffer is full and nobody is receiving
    fmt.Println(<-numbers)
}
fatal error: all goroutines are asleep - deadlock!

The buffer holds two values. The third send blocks, and since no other goroutine exists, Go reports a deadlock.

Q5. What happens when you use a nil channel?

Sending to or receiving from a nil channel blocks forever. In a select, a nil channel case is simply never chosen, which is a handy way to turn a case off.

Q6. What does this program print?

package main

import "fmt"

func main() {
    numbers := make(chan int, 3)
    for i := range 3 { // range 3 gives i = 0, 1, 2
        numbers <- i
    }
    close(numbers)

    sum := 0
    for number := range numbers {
        sum += number
    }
    fmt.Println(sum, len(numbers), cap(numbers))
}
3 0 3

The loop drains 0 + 1 + 2, which is 3. After that, the channel is empty, so len is 0, but cap stays 3.

select Questions

Q7. What does this program print?

package main

import "fmt"

func main() {
    channelA := make(chan string, 1)
    channelB := make(chan string, 1)
    channelB <- "from b" // only channelB has a value

    select {
    case message := <-channelA:
        fmt.Println(message)
    case message := <-channelB:
        fmt.Println(message)
    }
}
from b

Only channelB has a value, so only that case is ready. If both were ready, Go would pick one at random.

Q8. What does an empty select{} do?

It blocks forever. It is sometimes used at the end of main in small demo servers, but in real code, waiting on a signal or a context is better.

Q9. How do you run code on a schedule?

package main

import (
    "fmt"
    "time"
)

func main() {
    // A ticker sends on its channel ticker.C every 20 milliseconds.
    ticker := time.NewTicker(20 * time.Millisecond)
    defer ticker.Stop() // always stop tickers to free resources

    for i := 1; i <= 3; i++ {
        <-ticker.C // wait for the next tick
        fmt.Println("heartbeat", i)
    }
}
heartbeat 1
heartbeat 2
heartbeat 3

time.Ticker sends on its channel C at a fixed interval. Each loop waits for one tick and then prints a line. It is used for heartbeats, polling and periodic cleanup.

Design Questions on Go Channel Programs

Q10. Who should close a channel?

The sender, and only one of them. Receivers cannot know if more values are coming, and closing from the wrong side causes “send on closed channel” panics. With many senders, close after a WaitGroup says they are all done, as in Program 14.

Q11. Channels or mutexes?

Use channels to pass ownership of data or to signal events between goroutines. Use a mutex to protect a shared value, such as a counter or a cache. Both are correct tools; pick the one that makes the code clearer.

Q12. Do you have to close every channel?

No. Closing is only a signal for receivers that use range or need to know the stream has ended. A channel nobody waits on will be garbage collected when nothing refers to it.

Practice Task

Pipelines are a favourite among Go channel programs. Build one with three stages: the first sends numbers 1 to 20, the second keeps only multiples of 3, and the third adds them up and prints the total. Hint: copy the generate and square pattern from Program 9, and make the middle stage a filter.

Official Resources

Quick Recap

  • Go channel programs pass values between goroutines with ch <- v and <-ch.
  • Unbuffered channels make both sides meet, while buffered channels queue up to n values.
  • Close a channel from the sender side, and receive with range or v, ok.
  • select waits on many channels, and time.After adds timeouts.
  • Sending on or closing a closed channel panics, and a lone blocked send deadlocks.

What’s Next?

Next, we protect shared data and control how many goroutines work at once. Read Go mutex and worker pool programs, with safe counters, worker pools and context cancel. For interview practice, see the Go channels interview questions.