Golang Maps

Vishwas Javalgekar
2 min readMay 30, 2020

--

how to create, update, delete and loop through golang maps

Photo by Clément H on Unsplash

What is map in golang

A map is a builtin type in Go that is used to store key-value pairs, where each key is unique. all the individual keys needs to be a particular type and all the individual values of another type although the keys and values can be of different types.

Declaring map variables

following are ways to declare maps

//{declares empty map; key is of type int and value of type string}
1. var themap map[int]string
//{declares and initialises empty map using the make function}
2. themap := make(map[int]string)
//{one can declare and initialise at same time; pay attention to the comma after "green"}
3. colors := map[int]string{
1: "Voilet", 2: "Indigo", 3: "Blue",}

Appending and deleting values in a map

The syntax for adding new items to a map is the same as that of arrays, if you try to add to maps which have not been initialised it will result in “panic: assignment to entry in nil map”

colors[4] = "Green"colors[5] = "Yellow"and to delete, the below will delete the value with key 4 namely "Green"delete(colors,4)

Looping through a map

lets create a function(printMap) below to loop through the values of a map which gets passed as reference. the below function also showcases the use of len which gets us the length/size of the map.

func printMap(c map[int]string) {  fmt.Println("length of map is ", len(c))  for i, colorname := range c {    fmt.Println("item @", i, " colour name is ", colorname)  }}

Getting individual values of keys

Before retrieving a single value we want to check if that key-value exists in the map, below code show how to check and retrieve at the same time

colorFive, ok := colors[5]if ok == true {  fmt.Println(colorFive)}

--

--