Skip to content

Instantly share code, notes, and snippets.

@lmas
Created July 12, 2017 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmas/57851eacb97912b31c35b30b04effb56 to your computer and use it in GitHub Desktop.
Save lmas/57851eacb97912b31c35b30b04effb56 to your computer and use it in GitHub Desktop.
Reading values from a closed channel only returns zero values
package main
import (
"log"
)
func main() {
// Also works with other channel types, like: chan string, chan int etc.
// NOTE: The zero value for "bool" types is == false
ch := make(chan bool)
go func() {
// Send out a bunch of non-zero (true) values to the channel.
log.Println("goroutine start")
for i := 10; i > 0; i-- {
ch <- true
}
// Trying to read values from a closed channel will only return zero (false)
// values from it.
close(ch)
log.Println("goroutine stop")
}()
// Simulated "worker" that recieves values from the channel.
log.Println("main start")
for {
val := <-ch
log.Println("val =", val)
// If we get a zero value (false) from the channel it
// means it's been closed, time to quit.
if val == false {
break
}
}
log.Println("main stop")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment