Created
July 12, 2017 20:41
-
-
Save lmas/57851eacb97912b31c35b30b04effb56 to your computer and use it in GitHub Desktop.
Reading values from a closed channel only returns zero values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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