➰ Foreach loop in Go

introduction loop

There is no foreach loop in Golang, but the for loop can be adapted to work in the same way. In the example we first print out each word of strings array using loop pattern for {index}, {value} := range {array}. We don’t need index so it can be replaced with the blank identifier (underscore). We can also use this foreach loop for map elements. In the example, we print out a color of fruit using keys and values of the map.

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)
    }
}

Result:

Fruit: apple
Fruit: strawberry
Fruit: raspberry
apple color is green
strawberry color is red
raspberry color is pink

💤 While loop in Golang

Learn how to construct the popular programming while loop
introduction loop

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice