Let’s GO! Part 11: Reference Types 3: Maps

Ali Azizjahan
3 min readFeb 1, 2022
Hashmaps and Dictionaries?! In GO?!!

Overview

If you’re already familiar with some other languages like Java or Python, Maps in GO are exactly what we call them Hashmaps or Dictionaries respectively in those languages. They’re basically a key-value pair data structure that both the keys and the values are statically typed.

How Do They Work?

Exactly like Hashmaps and Dictionaries, Maps in GO are implemented using a hash table underneath. Now we’re not gonna go into how the hash tables work in this course. If you don’t know them already, there are pretty good articles out there about them that are only a Google search away from you!

Exactly like Hashmaps in Java, Maps in GO are not multi thread safe. This means if you are willing to write to or read from them in a concurrent manner, you need to implement a synchronization mechanism yourself. You can read more about how to do it safely in this article:

Code, Sweet Code!

First the syntax, which is really simple:

# First declare a map:
myMapName := make(map[KEY_TYPE]VALUE_TYPE)
# Then assign key-pair values to it:
myMapName[KEY] = VALUE

Pretty straightforward, right? Now let’s see it in action:

Maps in GO. Really easy!

The output should be:

myMap: map[one:1 two:2]
oneValue: 1 twoValue: 2
myMap after deletion: map[two:2]

Some important notes:

  • You can specify any types for the keys and the values. It’s really up to you and it’s very flexible.
  • The time order to search, insert and delete in maps are mostly constant. Meaning that they’ll be done in the most efficient way possible.
  • In Maps, unlike arrays and slices, if you iterate through them with a for loop, you’ll get different orders of key-value pairs in each iteration. Meaning that you can’t put a trust on the order of them.
  • In Maps, unlike structs, your keys should not be determined at the build time. You needed to tell GO that which keys your struct will be having when writing it and then you could use features like auto code completion on the key names provided by your IDE/Editor. But in Maps, you only tell GO that the keys will have what type, and then you can even make new keys with the same type at the runtime. Thus the auto code completion on the key names wouldn’t work. So be careful not to encounter errors about specifying wrong key names at runtime.

This is it! With Maps you’re now very powerful!

You’re powerful with Maps!

We’ll talk about Channels in the next part. 👀

Next:

Previous:

List Index:

--

--

Ali Azizjahan

Software Engineer and Computers Researcher. Teaching you the things that I wish I knew myself sooner, or I could be taught way easier. https://linktr.ee/kyxey