There is no foreach
loop and foreach
keyword in Go, but the usual for
loop can be adapted to work in a similar way. Using the range
keyword, you can create the range
form of the for
loop that is very useful when iterating over a slice or map. This kind of loop has the form of:
for <index>, <value> := range <array/slice> {
...
}
where:
<index>
is a numeric ordinal number that returns 0 for the first element in the array, 1 for the second, and so on<value>
is a copy of a slice/array element at that<index>
For maps, the for range
loop has <key>
instead of <index>
:
for <key>, <value> := range <map> {
...
}
where:
<key>
is the key of a given map entry<value>
is a copy of a map element at that<key>
Example
In the following example, we iterate through a slice and map to print each element. We do not need the <index>
to print the slice items, so it can be ignored using the blank identifier (underscore). In such a case, the for range
loop is almost identical to the foreach
known from other programming languages. When printing map items, we use the <key>
and <value>
to output the color (value) of the fruit (key).
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)
}
}
Output:
Fruit: apple
Fruit: strawberry
Fruit: raspberry
apple color is green
strawberry color is red
raspberry color is pink