Close a Go channel by calling close(ch) on the sender side to signal that no more values will be sent. Closing a channel prevents further sends (which would panic) and allows receivers to detect when the stream is finished via the ok value in the receive operation.
ch := make(chan int)
// Sender: send values then close
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
// Receiver: read until closed
for val := range ch {
fmt.Println(val)
}
// Loop exits automatically when ch is closed
Closing matters because it provides a clean way to signal completion in concurrent programs, allowing goroutines to exit loops gracefully without needing separate stop signals or timeouts.