首页 > 其他 > 详细

golang channel tips

时间:2018-06-30 14:24:15      阅读:225      评论:0      收藏:0      [点我收藏+]

 

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

 

golang channel tips

原文:https://www.cnblogs.com/dearplain/p/9246558.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!