Go core
Browse topics

Receiving from a closed channel

Version
1.27
Review
Draft

Summary#

Closing a channel signals that no more values will be sent. Receivers can drain buffered values and then observe that the channel is closed.

Syntax#

go
close(jobs)
value, ok := <-jobs

Example#

go
package main

import "fmt"

func main() {
	jobs := make(chan string, 2)
	jobs <- "first"
	jobs <- "second"
	close(jobs)

	for job := range jobs {
		fmt.Println(job)
	}
	remaining, ok := <-jobs
	fmt.Printf("%q %t\n", remaining, ok)
}

Expected output#

Text
first
second
"" false

Common mistakes#

Arrange for the sender or its coordinator to close the channel after all sends finish. Sending to a closed channel, closing it twice or closing a nil channel causes a panic. A receive on a drained closed channel returns the zero value with ok false. A receive on a nil channel blocks forever.

Version applicability#

Closing, draining and ranging over channels works this way in Go 1.27 and earlier Go versions.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0