Close the channel. Reading from a closed channel always succeeds, returning a respective zero value. The optional second boolean returned value indicates validity of the first value.
A receive expression used in an assignment or initialization of the form
x, ok = <-ch
x, ok := <-ch
var x, ok = <-ch
yields an additional result of type
bool
reporting whether the communication succeeded. The value ofok
is true if the value received was delivered by a successful send operation to the channel, or false if it is a zero value generated because the channel is closed and empty.
func printer(c <-chan int) {
for {
v, ok := <-c
if !ok { // chan closed
return
}
// v is valid
fmt.Println(v)
}
}
func provide() {
c := make(chan int)
go printer(c)
for i := 1; i <= 100; i++ {
c <- i
}
close(c)
}