DEV Community

Cover image for How to use Golang Maps?
Eternal Dev for Eternal Dev

Posted on • Originally published at eternaldev.com on

How to use Golang Maps?

What are maps?

Map is a built-in type in Go that helps in storing key-value pairs. One of the most useful data structures is Hash tables and Go provides this using Map. Hash tables are useful when you want fast lookup, adding, and deleting items.

The general structure of the map looks like the example below. Note that the keys in the table need to be unique and each key will have a single value associated with it. This helps in faster lookup time and ensures adding and deleting value is also fast.

{
    key = value,
    key2 = value2,
    key3 = value3
}
Enter fullscreen mode Exit fullscreen mode

When to use maps?

Map can be used when you know that the key associated with your value will be unique and you can have only one value for each key.

Let's consider an example,

You want to store the value of the number of likes for your post in a separate variable. You can use maps for that since each post will only have a single likes count. The post which is the key is also unique and there cannot be two posts with the same id.

Maps_example.jpg

Zero value of a map in Go

The zero value of a map is nil. So after creating the variable of a map, you will need to initialize the map variable using the make function. Setting the key value to a not initialized map variable will cause a runtime panic in Go.

Create and Initialize a map in Go

We can use the make function to initialize the map to an empty. After that, you can start adding items to the map and retrieve the values.

package main

import (
    "fmt"
)

func main() {
    var likes map[string]int
    likes = make(map[string]int)
    fmt.Println(likes)
}
Enter fullscreen mode Exit fullscreen mode

Declaring a variable called likes which is a map. The key of the map is string and the value is int. After the declaration of the variable, we have to call the make function and pass the type of the map to initialize it.

Output: map[]

There is also another way to initialize the map if you already know the entries which will be inside the map

package main

import (
    "fmt"
)

func main() {
    likes := map[string]int {
        "post1": 231,
    };
    fmt.Println(likes)
}
Enter fullscreen mode Exit fullscreen mode

Output: map[post1:231]

Adding items to map in Golang

Adding items to go map is similar to adding the value to the index of the key in array

package main

import (
    "fmt"
)

func main() {
    likes:= make(map[string]int)

    likes["post1"] = 211
    likes["post2"] = 2
    likes["post3"] = 623

    fmt.Println(likes)
}
Enter fullscreen mode Exit fullscreen mode

Adding items in Go Playground

The key of the map can be any of the comparable types in Go. It can be boolean, integer, float, etc.

Keys need to be comparable types because a map needs a way to compare and find the key and differentiate one key from another.

Getting items from the map in Golang

Getting items from the map is like accessing the data from the array.

package main

import (
    "fmt"
)

func main() {
    likes := map[string]int {
        "post1" : 12,
        "post2" : 234,
        "post3" : 53,
    }

    fmt.Println("Likes for the post", likes["post2"])
}
Enter fullscreen mode Exit fullscreen mode

Retrieving value from the map in Go Playground

Deleting items from map in Golang

delete(map, key) function can be used to delete the key from map

package main

import (
    "fmt"
)

func main() {
    likes := map[string]int{
        "post1": 12,
        "post2": 234,
        "post3": 53,
    }

    fmt.Println("Likes for the post", likes)
    delete(likes, "post1")
    fmt.Println("Likes for the post", likes)
}
Enter fullscreen mode Exit fullscreen mode

Delete item from map in Go Playground

Checking if a key exists in Golang

Golang returns the Zero value of the value type in the map when the key is not present

For example

package main

import (
    "fmt"
)

func main() {
    likes := map[string]int{
        "post1": 12,
        "post2": 234,
        "post3": 53,
    }

    fmt.Println(likes["postnotexist"])
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT : 0

postnotexist key is not present in the map and so Go will return the Zero value of the int which is 0. So we need a better way to check if the key exist or not. This can be achieved by setting the second variable which getting the value of the map.

package main

import (
    "fmt"
)

func main() {
    likes := map[string]int{
        "post1": 12,
        "post2": 234,
        "post3": 53,
    }

    value, ok := likes["postnotexist"]

    if ok {
        fmt.Println("Value of likes is", value)
    } else {
        fmt.Println("Value is not found")
    }
}
Enter fullscreen mode Exit fullscreen mode

More details - https://www.eternaldev.com/blog/how-to-check-if-a-map-contains-a-key-in-go/

Iterating over map in Golang

We can iterate the map using the range form.

package main

import (
    "fmt"
)

func main() {
    likes := map[string]int{
        "post1": 12,
        "post2": 234,
        "post3": 53,
    }

    for key, value := range likes {
        fmt.Println(key, value)
    }
}
Enter fullscreen mode Exit fullscreen mode

Iterating over map in Go Playground

Summary

We will have a detailed post next for practical usage of maps in Golang. Stay tuned to our blog and join our discord for more discussions

Discord - https://discord.gg/AUjrcK6eep

Discussion (0)