Maps

A map is a bit like a struct. But just a bit, actually it's kinda different.

As an example, let's say we are going to store some website URLs.

Create a new Map

// create a new map
websites := map[string]string{}

Here we create a new map with the name websites. We give the "key" identifier the datatype string and for the values we also use string and make an empty initialization.

We can also of course initialize it with values:

websites := map[string]string{
	"Google": "https://google.com",
	"Amazon": "https://amazon.com",
}

Mutating Maps

Now that we have this map, we can start to work with it. Let's say we want to extract the value by its key. So if we want to print the value of the key "Amazon" we need to use the following syntax:

fmt.Println(websites["Amazon"])

// Output:
https://amazon.com

Add new key-value pairs

Like on the slices and arrays, we can also add at anytime new key-value pairs to a map.

// This syntax can also be used to overwrite existing key-value pairs
websites["YouTube"] = "https://youtube.com"

Of course, we also have the possibility to delete the key-value pairs with the following syntax:

// We are passing the map and the key
delete(websites, "Google")

Make Maps

We can use the make function to "make" / create maps. This is useful if we know before, or we can estimate how many entries the map will have. If we initialized it empty and populate it, Go would have to reallocate memory to it. With this variant we have already our map which got its memory resources.

foodRatings := make(map[string]float64, 4)

If we add more than 4 entries as defined, Go will start to reallocate the memory.

Loop through Maps

If we want to clearly see the content of a map, lets say the key and the value of each pair, we can loop through the map. There are 2 ways to do this.

The first way you will automatically think of is:

foodRatings := map[int]string{}
foodRatings[0] = "Pizza"
foodRatings[1] = "Bread"
foodRatings[2] = "Tomato"
fmt.Println(len(foodRatings))

for i := 0; i < len(foodRatings); i++ {
    fmt.Println(foodRatings[i])
}

// Output:
Pizza
Bread
Tomato

But there is an easier way with the range keyword.

for index, value := range foodRatings {
    fmt.Printf("\nId: %v\nFood: %v\n", index, value)
}

Here, we define two variables inside our for loop. The index (the key) and the value (the value).

Look at this beautiful output:

Id: 0
Food: Pizza

Id: 1
Food: Bread

Id: 2
Food: Tomato

This is very useful for maps. For arrays, it can also be used if you really need the index. When not, use this instead for the values only.

Last updated