小编典典

Go中有foreach循环吗?

go

foreachGo语言中有结构吗?我可以使用 a 迭代切片或数组for吗?


阅读 228

收藏
2021-10-24

共1个答案

小编典典

带有“range”子句的“for”语句遍历数组、切片、字符串或映射的所有条目,或通道上接收到的值。对于每个条目,它将迭代值分配给相应的迭代变量,然后执行该块。

举个例子:

for index, element := range someSlice {
    // index is the index where we are
    // element is the element from someSlice for where we are
}

如果你不关心索引,你可以使用_

for _, element := range someSlice {
    // element is the element from someSlice for where we are
}

下划线_空白标识符,一个匿名占位符。

2021-10-24