Foreach Loops: The Go Way

· 175 words · 1 minute read

The foreach keyword itself does not exist within Go, instead the for loop can be adapted to work in the same manner. The difference however, is by using the range keyword and a for loop together. Like foreach loops in many other languages you have the choice of using the slices’ key or value within the loop.

Example 1)

In our example, we iterate over a string slice and print out each word. As we only need the value we replace the key with an underscore.

package main

import "fmt"

func main() {

	myList := []string{"dog", "cat", "hedgehog"}

	// for {key}, {value} := range {list}
	for _, animal := range myList {
		fmt.Println("My animal is:", animal)
	}
}

foreach loop in golang

Example 2)

Likewise, if we want to iterate and loop over each entry in a map, as you would an array, you can in the same way.

package main

import "fmt"

func main() {

	myList := map[string]string{
		"dog":      "woof",
		"cat":      "meow",
		"hedgehog": "sniff",
	}

	for animal, noise := range myList {
		fmt.Println("The", animal, "went", noise)
	}
}

foreach loop in golang

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!