dongzu3511 2010-08-03 16:17
浏览 479
已采纳

使用Go检查通道是否具有可读取的值

How do I check whether a channel has a value for me to read?

I don't want to block when reading a channel. I want to see whether it has a value. If it does have one, I'll read it. If it doesn't have one (yet), I'll do something else and check back again later.

  • 写回答

6条回答 默认 最新

  • douxiangbiao1899 2010-08-03 16:24
    关注

    WARNING: This is no longer accurate, see the answer below.

    From the docs:

    If a receive expression is used in an assignment or initialization of the form

    x, ok = <-ch
    x, ok := <-ch
    var x, ok = <-ch
    

    the receive operation becomes non-blocking. If the operation can proceed, the boolean variable ok will be set to true and the value stored in x; otherwise ok is set to false and x is set to the zero value for its type

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?