Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
ch := make(chan int, 1)
ch <- 7
close(ch)
for v := range ch {
fmt.Print(v)
}
}7
- Expecting a deadlock:
closetellsrangethat no more values will come, so the loop ends after reading the buffered7. - Expecting
0after the7: a receive on a closed channel gives the zero value, butrangestops at the close instead of receiving it.
- What would happen without
close(ch)? - What does
v, ok := <-chgive after the loop, and why?