Go — Maps (basics)

Go’s version of other languages: Hash, and Dict, are called Maps.

To create a Map you can use the “make” function, here we create a map with type string for the keys, and type int for the values of the map:

To access a value on the map you can use the square bracket annotation, shown above (m[“k1”] = 7). You can also initiate a Map and instantiate values on the new map on the same line:

You can use the builtin function:len returns the number of key/value pairs when called on a map:

You can also delete members of the Map, by using the “delete” function, here deleting the key/value pair with the key “k2” on the map variable “m”:

When accessing a value on a map, it returns two values. The second value indicates whether or not the key was present on the map. This is useful when disambiguating between keys that are missing or keys that have “falsy” values like 0 or “”, which could evaluate to false on user-made logic checks. Optionally you can also just put in a blank identifier: “_”, to omit the value.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikolaj Johannes Skole Jensen

Fullstack developer living in Denmark. Experience with both Web- and App development.