Go Channel: Buffered vs Unbuffered
In this tutorial, you'll learn about Go Channel: Buffered vs Unbuffered. We cover key concepts, practical examples, and best practices.
Buffered vs unbuffered channels -- Choose the right channel type based on whether you need synchronous or asynchronous communication.
The Problem
Unbuffered channels block the sender until a receiver is ready. Buffered channels block only when the buffer is full. Using the wrong type causes deadlocks or unexpected blocking.
Wrong
ch := make(chan int)
ch <- 42 // Blocks forever if no receiver ready
Output:
// fatal error: all goroutines are asleep - deadlock!
Right
ch := make(chan int, 1) // Buffered
ch <- 42 // Non-blocking (buffer available)
val := <-ch // Read succeeds
// Unbuffered for synchronization:
sync := make(chan struct{})
go func() {
// Do work
sync <- struct{}{} // Signal completion
}()
<-sync // Wait for goroutine
Output:
// Buffered for async, unbuffered for sync
Prevention
- Unbuffered: synchronous, guarantees delivery
- Buffered: async, decouples sender and receiver
- Buffer size 1 is common for simple signaling
- Set buffer size based on expected backlog
- Too large buffers hide bugs (slow consumers)
Common Mistakes with channel buffered unbuffered
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
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