douzhushen_9776 2018-07-06 03:11
浏览 31
已采纳

在Go中循环循环

Correct me if I'm wrong, there are only 3 types of loops in Go.

Type1 (The most basic type, with a single condition):

for i <= 3 {...}

Type2 (Classical for-loop)

for j := 7; j <= 9; j++ {...}

Type3 (infinite loop rely on break)

for {...break}

Then I come across this for loop that sums the value from array

nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
    sum += num
}
fmt.Println("sum:", sum)//"sum: 9"

Is the above for-loop to be considered Type1 where it automatically applies <= and range of nums as max value? Can I in any way change the value? maybe I need two extra loops? Can we apply something like range + 2?

  • 写回答

2条回答 默认 最新

  • dqm74406 2018-07-06 03:15
    关注

    From Effective Go:

    The Go for loop is similar to—but not the same as—C's. It unifies for and while and there is no do-while. There are three forms, only one of which has semicolons.

    // Like a C for
    for init; condition; post { }
    
    // Like a C while
    for condition { }
    
    // Like a C for(;;)
    for { }
    

    It continues:

    If you're looping over an array, slice, string, or map, or reading from a channel, a range clause can manage the loop.

    for key, value := range oldMap {
            newMap[key] = value
    }
    

    From this I think of range loops as a for condition { } loop, where the condition (such as it is) is that the variables being designated as the values of the array/slice/string/map/chan are not nil, though in practice even explicitly nil values work

    for _, v := range []interface{}{nil, nil, nil, nil} {
        // will still iterate four times
    }
    

    In reality it might be more useful to think of Go's for loop as a contextual combination of a C-style for init; condition; post loop, a classical while loop, and a more modern foreach loop.

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

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题