How to use Golang Maps?
Tags: go, beginners
Published: 2021-10-19 03:39:38

---
title: How to use Golang Maps?
published: true
date: 
tags: go, beginners
canonical_url: https://eternaldev.com/blog/how-to-use-golang-maps
cover_image: https://www.eternaldev.com/static/0e6e415dc3171c8e7d7f2734e9287dcc/aa1b3/gomapsposter.webp
---

## 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
}
```

## 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](https://eternaldev.com/static/0a7ee87c12b70fbb448d7911da653f16/f9218/maps_example.jpg "Maps\_example")](/static/0a7ee87c12b70fbb448d7911da653f16/f9218/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](https://go.dev/blog/defer-panic-and-recover) 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.

```go
package main

import (
	"fmt"
)

func main() {
	var likes map[string]int
	likes = make(map[string]int)
	fmt.Println(likes)
}
```

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

```go
package main

import (
	"fmt"
)

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

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

```go
package main

import (
	"fmt"
)

func main() {
	likes:= make(map[string]int)
	
	likes["post1"] = 211
	likes["post2"] = 2
	likes["post3"] = 623
	
	fmt.Println(likes)
}
```

[Adding items in Go Playground](https://play.golang.org/p/cpSJx3W9JAX)

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.

```go
package main

import (
	"fmt"
)

func main() {
	likes := map[string]int {
		"post1" : 12,
		"post2" : 234,
		"post3" : 53,
	}
	
	fmt.Println("Likes for the post", likes["post2"])
}
```

[Retrieving value from the map in Go Playground](https://play.golang.org/p/yNYx7lMTLjJ)

## Deleting items from map in Golang

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

```go
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)
}
```

[Delete item from map in Go Playground](https://play.golang.org/p/XCnIm-F8sAZ)

## 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

```go
package main

import (
	"fmt"
)

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

**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.

```go
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")
	}
}
```

More details - [https://www.eternaldev.com/blog/how-to-check-if-a-map-contains-a-key-in-go/](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.

```go
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)
	}
}
```

[Iterating over map in Go Playground](https://play.golang.org/p/rLn08JGbHgM)

## 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](https://discord.gg/AUjrcK6eep)