0
0
Goprogramming~3 mins

Why Buffered and unbuffered channels in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could pass messages like dropping notes in a mailbox instead of handing them one by one?

The Scenario

Imagine you are passing notes in class by hand, one by one, waiting for your friend to read each note before you can pass the next. This is like sending data without any waiting space.

The Problem

This slow, step-by-step passing means you must wait for your friend to be ready every time. If they are busy, you get stuck, and the whole process slows down or even stops.

The Solution

Buffered channels act like a small mailbox where you can drop several notes at once without waiting. Your friend can pick them up later at their own pace, making the whole communication smoother and faster.

Before vs After
Before
ch := make(chan int)
ch <- 1 // blocks until receiver gets it
After
ch := make(chan int, 3)
ch <- 1 // does not block until buffer is full
What It Enables

Buffered and unbuffered channels let your programs talk smoothly, either waiting for each other or working ahead without getting stuck.

Real Life Example

Think of a coffee shop where orders are taken one by one (unbuffered) versus a place where orders are lined up on a counter for baristas to pick up when ready (buffered).

Key Takeaways

Unbuffered channels require sender and receiver to be ready at the same time.

Buffered channels allow sending multiple messages without immediate receiving.

This helps programs run efficiently without unnecessary waiting.