chyroc / stackoverflow-go-top-qa

stackoverflow 有关golang的高票问答
0 stars 0 forks source link

Go有没有foreach循环 #5

Open chyroc opened 7 years ago

chyroc commented 7 years ago

Go语言中有没有foreach结构?我可以用一个for遍历一个slice或者array吗?

chyroc commented 7 years ago

http://golang.org/doc/go_spec.html#For_statements

带有“range”子句的“for”语句会遍历数组,slice,字符串或map的所有条目,或在channel上接收到值。 对于每个条目,它将迭代值分配给相应的迭代变量,然后执行该代码块。

举个例子:

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
}

下划线,_,是空白标识符,即匿名占位符。