Closing Channels
Start with Closing Channels
In this lesson, explore closing 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 closing channels.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Closing a channel announces that no more values will be sent. A receiver can continue draining buffered values, then receives the zero value and ok == false.
Typically the sender that owns the channel closes it. Sending on a closed channel panics; closing twice also panics. Do not use channel closure as a universal task-cancellation mechanism.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
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() {
numbers := make(chan int, 2)
numbers <- 3
numbers <- 5
close(numbers)
for n := range numbers {
fmt.Println(n)
}
_, ok := <-numbers
fmt.Println("More data:", ok)
}
Output
3
5
More data: falseTrace what the program does
The range loop drains 3 and 5 and terminates when the closed channel is empty. The final receive reports ok=false.
Avoid common mistakes
- Only close when no sender can send again.
- Receiving from a closed channel is allowed; sending to one is not.
Try it yourself
Change the channel to hold three numbers; use a range loop to calculate their sum after closing it.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Closing 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.