Golang: everything you need to know about maps

Maps are pretty similar to dictionaries in Python. In the below, I define a map called red_paints. In this map, I detail the name of the specific red colours for a few companies.

When we define the map, we use map[string] string, which means: map[ where they keys in the map are of string type] and the values of the map are of string type.

So, in the below “Company1” is indeed a string and so is “Brilliant Red”. If we wanted to define “Company1” : 23, we would need to define it as map[string] int.

We can also define a map like the below:

Or even, like the below:

We can add new values to the dictionary too. In the below, we use map_name[key] = value. The below adds a new value to the dictionary with they key “Company4” and the value assigned to that key is “Ferrari Red”.

We can access specific keys in the map using the below notation. This is map_name[key name]. In this example the output would be “Ferrari Red”.

Next, we can delete items from a map using the notation delete( Map_name, Key). This would remove “Company4” : “Ferrari Red” from the map.

Finally, we can iterate over a map using the below. This is for key, value := range map_name. Here, we can name key and value whatever we like, the loop will assign the values from the map to those two variables each time it loops.

So, what’s the difference between a map and a struct?

  • A map is statically typed. If you define keys as strings then ALL keys must be strings and if you define values as integers they must ALL be integers.
  • You cannot iterate over structs
  • A map is a reference type & hence a pointer is not required, while it is with structs
  • Struct fields are defined at launch, whereas you can add and remove from a map.
Kodey