Channels let goroutines talk to each other. Closing a channel tells others no more values will come.
0
0
Channel closing behavior in Go
Introduction
When you finish sending data and want to tell receivers to stop waiting.
When you want to signal that a task is done.
When you want to avoid deadlocks by closing channels after use.
Syntax
Go
close(channelName)
You only close a channel from the sender side.
Closing a channel twice causes a panic (runtime error).
Examples
This creates a channel and then closes it immediately.
Go
ch := make(chan int)
close(ch)Looping over a channel stops automatically when the channel is closed.
Go
for v := range ch {
fmt.Println(v)
}Reading from a closed channel returns zero value and ok=false.
Go
v, ok := <-ch if !ok { fmt.Println("Channel closed, no more data") }
Sample Program
This program sends numbers 1 to 3 into a channel, then closes it. The main goroutine reads and prints all values until the channel closes. Then it tries to read once more to show the zero value and ok=false after closing.
Go
package main import ( "fmt" ) func main() { ch := make(chan int) go func() { for i := 1; i <= 3; i++ { ch <- i } close(ch) }() for v := range ch { fmt.Println(v) } v, ok := <-ch fmt.Printf("After close: value=%d, ok=%v\n", v, ok) }
OutputSuccess
Important Notes
Do not send on a closed channel; it causes a panic.
Receivers can detect channel closure by checking the second value from receive.
Closing a channel is optional but useful to signal no more data.
Summary
Use close(channel) to tell receivers no more values will come.
Reading from a closed channel returns zero value and ok=false.
Looping with for v := range channel stops when channel closes.