Closing Channels
Close a channel to broadcast completion; only senders should close.
A channel passes values between goroutines, functions started with go that can run while their caller continues. Closing a channel tells receivers that no more values will be sent. They can still receive values already waiting in the channel. After those are read, a receive returns the type's zero value, its default such as 0 for an integer.
The two-result receive form returns the value and an ok boolean. ok is false when the channel is closed and empty, so the receiver can tell the difference between a real zero value and no more values.
package main
import "fmt"
func main() {
jobs := make(chan int, 2)
jobs <- 1
jobs <- 2
close(jobs)
for {
job, ok := <-jobs
if !ok {
break
}
fmt.Println(job)
}
}In production
The code that sends values should close a channel only after all sends have finished. If there are several senders, have one part of the program wait for all of them, then close the channel. Closing while another goroutine is sending can still cause a panic.