Closing channels
Context
Section titled “Context”You can close a channel with close(ch). Receivers can test whether a channel is closed using the comma‑ok idiom: v, ok := <-ch. Sending on a closed channel causes a panic.
Example
Section titled “Example”Close a channel and detect the closure.
Code example
Section titled “Code example”package main
import "fmt"
func main() { ch := make(chan int, 2) ch <- 1 ch <- 2 close(ch)
for i := 0; i < 3; i++ { v, ok := <-ch fmt.Printf("value=%d, ok=%t\n", v, ok) }}Output
Section titled “Output”value=1, ok=truevalue=2, ok=truevalue=0, ok=false