Go中有foreach循环吗?

问题描述

https://golang.org/ref/spec#For_range

带有“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
}

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

解决方法

Go 语言中有foreach构造吗?我可以使用 a 遍历切片或数组for吗?