Skip to content

Is There a Foreach Loop in Go? [YES]

If you came from the PHP or JS world then you want to know how you can write a foreach loop in the Golang 🙂

If you want to iterate over a slice:

package main

import "fmt"

func main() {
	mySlice := []int{1, 2, 3, 4, 5}

	// Full: index and value
	for index, value := range mySlice {
		fmt.Println(index, ":", value)
	}

	// Only: index / The index starts from 0 in golang
	for index := range mySlice {
		fmt.Println(index)
	}

	// Only: item
	for _, value := range mySlice {
		fmt.Println(value)
	}
}

For the map:

package main

import "fmt"

func main() {
	myMap := map[string]int{
		"Cats": 32,
		"Dogs": 43,
	}

	// Full: key and value
	for key, value := range myMap {
		fmt.Println(key, ":", value)
	}

	// Only: key
	for key := range myMap {
		fmt.Println(key)
	}

	// Only: value
	for _, value := range myMap {
		fmt.Println(value)
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *