dongqiang8058 2019-05-15 05:38 采纳率: 100%
浏览 36
已采纳

跨频道范围还是使用select更好?

guys i was wondering if it is better to to range over channel or use select, if I have only one case (my channel) and signal the end with close of the given channel ?

Given the examples:

1. https://play.golang.org/p/3ZFdbgHSKyN

go func() {
    for v := range ch {
        // do some stuff
    }
}()

2. https://play.golang.org/p/iCCkDge8j72

go func() {
    for {
        select {
        case v, ok := <-ch:
            if !ok {
                return
            }

            // do some stuff
        }
    }
}()

Which solution would be preferred and why ? Please consider the fact that goroutines as such might be spawned many times (many workers).

  • 写回答

1条回答 默认 最新

  • douchongbc72264 2019-05-15 12:45
    关注

    Unless there's another branch of the select, use the following:

    for v := range ch {
        // do some stuff
    }
    

    The code is simpler and easier to understand than the for/select presented in the question.

    If you need to do the receive inside the loop for some reason, then use the following code:

     for  { 
         // do some stuff
         v, ok := <-ch
         if !ok { 
            break 
         } 
         // do some other stuff
     }
    

    As a rule of thumb, single branch select statements should be avoided. A select with a single branch is functionally the same as the branch alone.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题