Tags: #go #golang #channel #close
A common pattern for indicating something is done is to create an unbuffered channel of type struct{}
and then close
the channel will unblock anything trying to retrieve a value from the channel.
Note: the reason for using
struct{}
type is because it’s the smallest sized type in Go (no allocations are made).
Below is an example that demonstrates how closing a channel means you can still take values from the channel, but that they’ll be the default value of the given type.
package main
import "fmt"
func main() {
c := make(chan bool)
go func() {
c <- true // blocks until someone takes value
}()
fmt.Println(<-c) // true pulled from channel
close(c)
fmt.Println(<-c) // false which is default value of bool type
}