➰ Foreach loop in Go

March 26, 2021
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)


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

✒️ Write to a CSV file in Go

Learn how to write data to a CSV or TSV file
introduction file

🙌 Case-insensitive string comparison in Go

May 25, 2021
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings