golang channel tips

1. 读nil的channel是永远阻塞的。关闭nil的channel会造成panic。


2. closed channel的行为:

向close的channel发消息会panic。因为go建议向channel发送数据的人负责close channel。

如果close的channel还有数据,仍然可以读取。

读取close的并且空的channel,会马上返回零值(注意chan int会返回0)。

A channel "close" is really just a send of a special value on a channel. 


3. 可以对channel使用range。这样不用写select,显得代码简洁。


4. ok=false表示channel空并且close了 (注意不是“或者”)。

参考:

https://stackoverflow.com/questions/34897843/why-does-go-panic-on-writing-to-a-closed-channel

猜你喜欢

转载自www.cnblogs.com/dearplain/p/9246558.html