Andrew's Digital Garden

Maps in Go

Maps store key/value pairs, and are declared with two types: one for keys and one for values:

data := map[string]int

A map does not sort its keys, and the keys need to be comparable through == and !=. Thus, don't use floating points for keys, as rounding errors may occur. If you want to use a key type that is not comparable, write a helper function to turn that type into a unique string.

Composite literals can be used to create and allocate values into a map:

moons := map[string]int{ "Earth": 1, "Mars": 2, "Jupiter": 67, "Saturn": 62, }

If you want to test if a retrieved element exists in the map, use the “comma, ok” idiom [[20200720095858-go-ok]]:

venusMoons, ok := moons["Venus"]

range can be used to loop over maps, and will return the key and value. [[20200309192016-go-for]]. The result is not ordered at all.

[[go]]

Referred in

Maps in Go