Go Channel Fan-In Pattern — Complete Guide
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
Right
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
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- 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
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