Signup/Sign In
PUBLISHED ON: FEBRUARY 17, 2023

Maps in GoLang

A Map in Golang is a special type of data structure that is used to store a collection of unordered pairs of items. In this pair, one item is the key and the other is known as the value. It is a built-in type in Go. Maps are ideal for the cases when we want to do a look-up for specific values using keys in a very fast manner.

Maps are common in different programming languages, with different names. In python, we refer to them as dictionaries, in Java we have HashTables, and so on.

How to declare a Map in Golang?

In this section, we will learn how we can create a simple map in Go. Let's consider the case that we want to store information about the employees of the company. We want to store the salary of the employees which we can later extract by their names. For such cases, a map is the ideal data structure that one can use. Below is an example, where I have created a map called employeeData where the key is the name of the employee, and the salary will be the value.

Consider the code shown below as a reference.

package main

import (
	"fmt"
)

func main() {
	var employeeData map[string]int
	fmt.Println(employeeData)
}

We can also assign values to this map, but we will do that in the later section in the same article. For now, just focus on the syntax of declaring a simple map. We make use of the map keyword which is followed by [string] which simply means that we want the key of type string( the name of the employee ) in our case and then it is followed by int which means that the value of the key will be of type int( the salary of the employee ).

map[]

How to initialize a map in Golang?

In the previous section, we learned how we can declare a map in Go, in this section I'll talk about how we can initialize it as soon as we are declaring it. The idea is that we make use of curly braces to put the data into the map as soon as it is declared. This way we won't have to assign the data in separate lines.

Consider the example shown below where we are creating a map named employeeData where we are also inserting the employee name-salary key-value pairs at the same time as initialization.

package main

import (
	"fmt"
)

func main() {
	var employeeData = map[string]int{"rahul": 100, "sneha": 130}
	fmt.Println(employeeData)
}

Notice how we can write the key-value pairs by making use of the curly braces in the above code. One more thing to note is that in the above example, we are using the = operator when we are doing both the initialization and the assignment and it is very important. If you forget to put the = symbol, then the Go compiler will throw an error.


map[rahul:100 sneha:130]

How to declare an empty map in Golang?

We can also declare an empty map in Go. The approach behind that is we make use of empty braces when declaring and initializing the array.

Consider the code shown below where an empty map named employeeData is declared.

package main

import (
	"fmt"
)

func main() {
	var employeeData = map[string]int{}
	fmt.Println(employeeData)
	fmt.Printf("%T\n", employeeData)
}

In the above example, we are printing two things as well, the first being the map's value and the second being the type of the map. In Go, we make use of the %T format specifier to print the type of a built-in type in Go.

map[]
map[string]int

Zero value of a Map in Golang

Maps when declared without any initialization have zero values, and that value is always nil. If we add elements to an empty map, we will get a runtime panic error. That is why it is always recommended to initialize a map before adding elements to it.

Consider the code shown below that depicts an empty map.

package main

import (
	"fmt"
)

func main() {
	var employeeData map[string]int
	fmt.Println(employeeData)
	employeeData["rahul"] = 100
}

Notice how I am trying to add a new element to the map in the last line of the main function.

map[]
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
/tmp/sandbox3920387835/prog.go:10 +0x69

Declaring a Map using make function in Golang

Go provides us with a make function that can be used in declaring a map. The make function accepts a type(,length and capacity) as an argument and then it returns an initialized map. It is the most widely used approach when declaring a map in Go.

Consider the code shown below where a map named employeeData is declared using the make function.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140

	fmt.Println(employeeData)
}

It should be noted that the only difference in the previous examples, and the above example, is the make function keyword.

map[rahul:120 shreya:140]

Find the length of a Map in Golang

We can make use of the len() function that Go provides us to calculate the number of key-value pairs present in a map. To use it, just pass the name of the map as an argument to the len() function and it will return an integer value.

Consider the code shown below where we are using the len() function on two maps, the first map has some elements in it, while the second one is empty.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140

	fmt.Println(len(employeeData))

	var methodsMap = make(map[int]int)

	fmt.Println(len(methodsMap))
}


2
0

How to add items to a Map in Golang

Let's consider one example where we will add the items and then print the map.

Consider the code shown below.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["mukul"] = 170

	fmt.Println("Map:", employeeData)
}

One important point to note is that we inserted the key-value pairs in a certain manner, but it isn't necessary that when we print the map we will get the elements in that same manner.

Map: map[mukul:170 rahul:120 shreya:140]

How to access items from a Map in Golang?

To access items from a map, we make use of the [](square bracket notations). The approach is to pass the key into these square brackets, and then the returned value will be the value that is present in the map for the passed key. If we somehow pass a key that is not present in the map, then a zero value of the value type will be returned as the answer.

Consider the code shown below where both the cases of retrieving values mentioned above are depicted.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["mukul"] = 170

	salaryMukul := employeeData["mukul"]

	fmt.Println("Salary of Mukul is:", salaryMukul)

	salaryX := employeeData["X"]

	fmt.Println("Salary of X is:", salaryX)
}

The second time we are trying to access an item, we passed the key as "X" which is not present in the employeeData map, hence the value that we will get in return is the zero value of int type which is simply 0.

Salary of Mukul is: 170
Salary of X is: 0

How to check if a key exists in a Map in Golang?

One of the most used cases when it comes to working with maps is doing something after we have checked that this key exists in the map. To check whether a key exists in a map or not, we will make use of the same syntax of accessing the elements from a map, but with a minor tweak.

Consider the code shown below where we check whether a specific employee name exists in the map or not, and if it does then we print something, if not, then we print something else.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["mukul"] = 170

	if _, ok := employeeData["mukul"]; ok {
		fmt.Println("The key named mukul exists in the map")
	} else {
		fmt.Println("No key named mukul exists in the map")
	}
}


The key named mukul exists in the map

How to update values in a Map in Golang?

We can update the values of a specific item in a map by simply referring to its key name.

Consider the example shown below where we will update the salary of a particular employee in the employeeData map.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["mukul"] = 170

	fmt.Println("Before updation:", employeeData)

	employeeData["shreya"] = 165

	fmt.Println("After updation:", employeeData)
}


Before updation: map[mukul:170 rahul:120 shreya:140]
After updation: map[mukul:170 rahul:120 shreya:165]

How to delete items from a Map in Golang?

We can also delete the key-value pairs from the map by making use of the built-in delete function. The delete function takes two arguments, where the first argument is the name of the map, and the second argument is the key that you want to delete.

Consider the code shown below where we will delete the key named "rahul" from the map.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["mukul"] = 170

	fmt.Println("Before deletion:", employeeData)

	delete(employeeData, "rahul")

	fmt.Println("After deletion:", employeeData)
}

Before deletion: map[mukul:170 rahul:120 shreya:140]
After deletion: map[mukul:170 shreya:140]

Maps are reference types in Golang

We learned about reference types in Slices, that if we assign a map to a new variable and if we make any change in that variable, then that change will also be reflected in the original map as well.

Consider the example shown below where we depict the above-mentioned case.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["mukul"] = 170

	newMap := employeeData
	
	newMap["mukul"] = 199

	fmt.Println(newMap)
	fmt.Println(employeeData)
}


map[mukul:199 rahul:120 shreya:140]
map[mukul:199 rahul:120 shreya:140]

Iterating over all elements of a map in Golang

The most commonly used approach when we want to iterate over a map is to make use of the range clause. The range form of the for loop simply iterates over all the elements, and each iteration returns the key and the value as well.

Consider the example shown below where I am using the range form of the for loop to iterate over the employeeData map.

package main

import "fmt"

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["mukul"] = 170

	for key, val := range employeeData {
		fmt.Println(key, " -> ", val)
	}
}


rahul -> 120
shreya -> 140
mukul -> 170

How to truncate a Map in Golang?

Truncating a map means that we are deleting all the entries from the map. In Go, there are two approaches that we can follow in case we want to truncate a map. The first approach is to make use of the delete() function on all the values of the map and the second approach is to simply reassign the map to a new map using the make function.

Consider the code shown below where both these approaches mentioned above are depicted.

package main

import "fmt"

func main() {
	var employeeDataOne = make(map[string]int)
	employeeDataOne["rahul"] = 120
	employeeDataOne["shreya"] = 140
	employeeDataOne["mukul"] = 170

	// Approach 1
	for key, _ := range employeeDataOne {
		delete(employeeDataOne, key)
	}

	fmt.Println(employeeDataOne)

	var employeeDataTwo = make(map[string]int)
	employeeDataTwo["rahul"] = 110
	employeeDataTwo["shreya"] = 130

	// Approach 2
	employeeDataTwo = make(map[string]int)

	fmt.Println(employeeDataTwo)
}


map[]
map[]

How to sort map keys in Golang?

To sort the map keys, we are making a slice of the same type of the map key's type and then we are passing that slice as an argument to the sort package's Strings() function that will sort all the values in that slice.

Consider the code shown below.

package main

import (
	"fmt"
	"sort"
)

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["akshay"] = 199
	employeeData["mukul"] = 170

	keys := make([]string, 0, len(employeeData))

	for k := range employeeData {
		keys = append(keys, k)
	}

	sort.Strings(keys)

	for _, key := range keys {
		fmt.Println(key, employeeData[key])
	}
}


akshay 199
mukul 170
rahul 120
shreya 140

How to sort map values in Golang?

We can sort the key's values, in the same manner, we sorted the keys. If we consider the same map named employeeData, the only difference will be the sort packages Ints() function, as the type of the values in the map is of type int.

Consider the code shown below where we are sorting the values of a map and then printing them.

package main

import (
	"fmt"
	"sort"
)

func main() {
	var employeeData = make(map[string]int)
	employeeData["rahul"] = 120
	employeeData["shreya"] = 140
	employeeData["akshay"] = 199
	employeeData["mukul"] = 170

	values := make([]int, 0, len(employeeData))

	for _, value := range employeeData {
		values = append(values, value)
	}

	sort.Ints(values)

	for _, v := range values {
		fmt.Println(v)
	}
}


120
140
170
199

How to merge Maps in Golang?

We can merge two maps by iterating over one of the maps and then inserting the values of that map into the other map.

Consider the code shown below that shows how we can merge two maps in Go.

package main

import (
	"fmt"
)

func main() {
	var employeeData = make(map[string]int)
	var anotherMap = make(map[string]int)

	employeeData["mukul"] = 100
	employeeData["mayank"] = 101
	employeeData["deepak"] = 102

	anotherMap["mukul"] = 199

	for k, v := range employeeData {
		anotherMap[k] = v
	}

	fmt.Println(employeeData)
	fmt.Println(anotherMap)

}


map[deepak:102 mayank:101 mukul:100]
map[deepak:102 mayank:101 mukul:100]

How to check if two Maps are equal in Golang?

To check whether the two maps are equal or not, we can make use of the reflect.DeepEqual() function.

Consider the code shown below that depicts how we can compare two maps for equality.

package main

import (
	"fmt"
	"reflect"
)

func main() {
	var employeeData = make(map[string]int)
	var anotherMap = make(map[string]int)

	employeeData["mukul"] = 100
	employeeData["mayank"] = 101
	employeeData["deepak"] = 102

	anotherMap["mukul"] = 199

	if reflect.DeepEqual(employeeData, anotherMap) == true {
		fmt.Println("Maps are Equal")
	} else {
		fmt.Println("Maps aren't equal")
	}
}


Maps aren't equal

Conclusion

In this article we learned pretty much every use case of Maps in Golang, beginning with the definition, then moving on to the different types of declaration and initialization that we can use for a map. Then we learned about the len() function use case on maps, followed by how we can access and add items into a map. Then we learned about how we can delete items from a map, followed by how we make use of the range for loop to iterate over all the elements of the map, then we talked about sorting the keys and values of the map, and lastly, we saw two examples, where in the first one we tried to merge maps and in the last example, we checked the equality of two maps.



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.