This is a creation in Article, where the information may have evolved or changed.
Reprint: http://my.oschina.net/goskyblue/blog/191149
Channel
Sample1 Close twice
ch := make(chan bool)close(ch)close(ch) // 这样会panic的,channel不能close两次
The channel was closed early when it was read.
ch := make(chan string)close(ch)i := <- ch // 不会panic, i读取到的值是空 "", 如果channel是bool的,那么读取到的是false
Write data to a channel that has been closed HTTP://PLAY.GOLANG.ORG/P/VL5D5TKFL7
ch := make(chan string)close(ch)ch <- "good" // 会panic的
Determine if the channel is close
i, ok := <- chif ok { println(i)} else { println("channel closed")}
For Loop Read Channel
for i := range ch { // ch关闭时,for循环会自动结束 println(i)}
Prevent read Timeouts
select { case <- time.After(time.Second*2): println("read channel timeout") case i := <- ch: println(i)}
Prevent write Timeouts HTTP://PLAY.GOLANG.ORG/P/AODFPNWDMJ
// 其实和读取超时很像select { case <- time.After(time.Second *2): println("write channel timeout") case ch <- "hello": println("write ok")}