How to iterate over a map in Go

You can iterate over maps in Go but, unlike slices, the order of iteration is not guaranteed. There are ways to get around this, and that is what we'll examine in this snippet.

The basic way to iterate over a Go map is by using the for..range loop construct. Instead of receiving index/value pairs as with slices, you get key/value pairs for maps. Note that the order may be randomised so you cannot rely on a specific order of iteration.

func main() {
	m1 := map[string]int{
		"a": 1,
		"b": 2,
		"c": 3,
	}

	for key, value := range m1 {
		fmt.Println(key, "->", value)
	}
}

// Output:
// b -> 2
// c -> 3
// a -> 1

That’s all well and good, but what if you need the iteration order to be guaranteed? Here’s a workaround you can use.

Thanks for reading, and happy coding!