ProgramGuru

Buffered Channels

Start with Buffered Channels

In this lesson, explore buffered channels through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of buffered channels.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

make(chan T, capacity) allows up to capacity values to wait in a channel without an immediate receiver. Send blocks when the buffer is full; receive blocks when it is empty.

Capacity reduces some waiting but does not eliminate backpressure or guarantee fairness.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for buffered channelsThe buffer holds values until the consumer receives them.Capacity: 2Step 1Send firstStep 2Send secondStep 3Receive in orderStep 4The buffer holds values until the consumer receives them.
The buffer holds values until the consumer receives them.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	jobs := make(chan string, 2)
	jobs <- "first"
	jobs <- "second"
	fmt.Println("Queued:", len(jobs), "Capacity:", cap(jobs))
	fmt.Println(<-jobs, <-jobs)
}

Output

Queued: 2 Capacity: 2
first second

Trace what the program does

Two sends fit into the buffer and the program prints the length and capacity as 2. Values come out in send order.

Avoid common mistakes

  • Buffer capacity is not a maximum number of goroutines.
  • A full buffer still blocks the next send.

Try it yourself

Change the buffer to capacity 3 and send three values before receiving them.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What happens when a buffered channel is full?
Choose one answer. You can try again.

Answer and explanation

Another send blocks until space becomes available

Correct. Two sends fit into the buffer and the program prints the length and capacity as 2.

What you should remember

You have practiced Buffered Channels in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Sending and Receiving Data →