Skip to content

Go Channel Fan-In Pattern — Complete Guide

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Go Channel Fan. We cover key concepts, practical examples, and best practices.

Channel fan-in -- Merge multiple input channels into a single output channel for unified processing.

The Problem

Fan-in combines multiple input channels into one. Use a goroutine with select to read from all inputs, or use a separate goroutine per input channel.

Wrong

ch1 := make(chan int)
ch2 := make(chan int)
// How to merge both into one channel?

Output:

// Need fan-in pattern to combine channels
func fanIn(ctx context.Context, channels ...<-chan int) <-chan int {
    out := make(chan int)
    var wg sync.WaitGroup
    multiplex := func(ch <-chan int) {
        defer wg.Done()
        for val := range ch {
            select {
            case out <- val:
            case <-ctx.Done():
                return
            }
        }
    }
    wg.Add(len(channels))
    for _, ch := range channels {
        go multiplex(ch)
    }
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}

Output:

// Merged output channel from all inputs

Prevention

  • Use one goroutine per input channel for fan-in
  • Close output when all inputs are closed
  • Use select to allow context cancellation
  • WaitGroup tracks when all inputs are done
  • Fan-in preserves order within each input but not across inputs

Common Mistakes with channel fan in

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does fan-in preserve order?**

Order within each input is preserved. Across inputs, order depends on timing.

Can I fan-in without goroutines?

Use a single goroutine with select reading all inputs.

What happens if one input closes?

Other inputs continue. Output closes when all close.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro