Cookies management by TermsFeed Cookie Consent

➰ Foreach loop in Go

Last updated:
introduction loop syntax

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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

♾️ 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

β€οΈβ€πŸ©Ή Recover function in Go

Learn what it is for and how to use the built-in recover() function
introduction syntax builtin