Golang maps

Maps

Map is a data structure that implements hash table

Creating Maps

In order to create a map in go we should use make, it allocates memory to store the map data.

myMap := make(map[keyType]valueType)

An example of how to create a map is above.

Optionally we can create a map with a defined initial capacity, it may benefit a better application performance, since the need of memory reallocation may be reduced.

myMap := make(map[string]string, 10)

Inserting new elements in a map

An example of how to bind a value to a key is below.

myMap["key"] = "value"

Getting a value from a key

An example of how to get a value from a key is below.

myValue := myMap["key"]
fmt.Println(myValue)
>> value

There might be some situations that the key doesn’t exist in the map, go has a way to check the existence of the key in a map.

myMap := make(map[string]string)
myMap["animal"] = "cat"

value, exists := myMap["golang"]
fmt.Println(exists)
>> false

If you get a value from a nonexistent key, this value will be the zero one for the type in the map.

Iteration in maps

We can iterate all elements inside a map trough range.

myMap := make(map[string]string)
myMap["country"] = "Brasil"
myMap["city"] = "Sao Paulo"
myMap["park"] = "ibirapuera"

for key, value := range myMap {
    fmt.Printf("My key: %s, my value: %s\n", key, value)
}
>> My key: country, my value: Brasil
>> My key: city, my value: Sao Paulo
>> My key: park, my value: ibirapuera

Removing an Element

We can remove an element from a map trough delete function

myMap := make(map[string]string)
myMap["country"] = "Brasil"
myMap["city"] = "Sao Paulo"
myMap["park"] = "ibirapuera"

for key, value := range myMap {
    fmt.Printf("My key: %s, my value: %s\n", key, value)
}

delete(myMap, "park")

fmt.Println("After delete")

for key, value := range myMap {
    fmt.Printf("My key: %s, my value: %s\n", key, value)
}
>> My key: country, my value: Brasil
>> My key: city, my value: Sao Paulo
>> My key: park, my value: ibirapuera
>> After delete
>> My key: country, my value: Brasil
>> My key: city, my value: Sao Paulo

Map length

We can get the map length through the len function

meuMapa := make(map[string]string)
meuMapa["pais"] = "Brasil"
meuMapa["cidade"] = "Sao Paulo"
meuMapa["parque"] = "ibirapuera"

fmt.Println(len(meuMapa))
>> 3

Nested maps

An example of how to work with nested maps is below:

myMap := make(map[string]map[int]string)
myMap["city"] = make(map[int]string)
myMap["city"][0] = "Sao Paulo"
myMap["city"][1] = "Rio de Janeiro"

for key, value := range myMap {
    for innerKey, innerValue := range value {
        fmt.Printf("Key: %s, innerKey: %d, innerValue: %s\n", key, innerKey, innerValue)
    }
}
>> Key: city, innerKey: 0, innerValue: Sao Paulo
>> Key: city, innerKey: 1, innerValue: Rio de Janeiro