go empty channel

tags: learning go programming

content

  • reading from an empty channel or a closed channel will not cause panic
  • but writing into a closed channel will cause panic
func main() {
	ch := make(chan, int, 1)
	ch <- 1
	close(ch)
	fmt.Println(<-ch) // reading from closed channel, no prob! whatever is in the channel is fetched
	fmt.Println(<-ch) // reading from empty channel, get a 0
	ch <- 2  // panic!
}

up

go-channel-basics

down

reference