Go by Example

Closing Channels

Close a channel to broadcast completion; only senders should close.

Closing a channel signals that no more values will be sent. Receivers can still read buffered values; after those are drained, receives return the zero value.

The comma-ok receive reports whether a value was read. ok becomes false when the channel is closed and empty.

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 sender that owns a channel should close it after all sends finish. With multiple senders, coordinate their completion and close from one coordinator. sync.Once can prevent duplicate closes, but by itself it does not make a send concurrent with close safe.

Enjoyed this? Get more software craft delivered to your inbox.