在Golang中没有foreach 循环,但是for 循环可以用同样的方式来工作。在这个例子中,我们首先使用循环模式for {index}, {value} := range {array} ,打印出字符串数组的每个字。我们不需要index ,所以它可以用空白标识符(下划线)代替。我们也可以对地图元素使用这个foreach 循环。在这个例子中,我们使用地图的键和值打印出水果的颜色。
func main() {
// array foreach loop
fruits := []string{"apple", "strawberry", "raspberry"}
for _, fruit := range fruits {
fmt.Printf("Fruit: %s\n", fruit)
}
// map foreach loop
fruitColors := map[string]string{
"apple": "green",
"strawberry": "red",
"raspberry": "pink",
}
for fruit, color := range fruitColors {
fmt.Printf("%s color is %s\n", fruit, color)
}
}
结果
Fruit: apple
Fruit: strawberry
Fruit: raspberry
apple color is green
strawberry color is red
raspberry color is pink