Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

➰ Foreach or for range loop in Go

introduction loop syntax

Please consider supporting us by disabling your ad blocker

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:

For maps, the for range loop has <key> instead of <index>:

for <key>, <value> := range <map> {
    ...
}

where:

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

♾️ Infinite loop in Go

Learn how to define a "while true" loop
introduction loop

💤 While loop in Golang

Learn how to construct the popular programming while loop
introduction loop

🦥 Ternary operator in Go

Learn how to substitute a ternary operator not available in Go
introduction syntax