Table of contents
1.
Introduction
2.
Creating Maps in Go
2.1.
Using var Keyword
2.2.
Using := Operator
2.3.
Using the make() Function
2.4.
Creating Empty Maps
3.
Accessing Elements in a Map
4.
Updating and Adding Elements in a Map
5.
Remove an Element From a Map 
6.
Check for a specific element in a map
7.
Iterating Over Maps
8.
Maps are Reference Types
9.
Need For Maps
10.
FAQs
11.
Key Takeaways
Last Updated: Mar 27, 2024

Go Map

Author ANKIT KUMAR
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Maps are one of the most useful and helpful data structures supported by most modern programming languages. A map in Go is an unordered collection of key-value pairs. It maps keys to values. The keys are unique within a map, while the values may not be.

Maps are highly useful when we want to check if a particular key exists or not. Using maps is not at all cumbersome.

Creating Maps in Go

There are multiple ways to create a map in Go. We shall discuss them one by one.

Using var Keyword

Syntax:

var map_name = map[KeyType]ValueType{key1:value1, key2:value2,...}

Example:

package main
import "fmt"


func main() {
    
    // creating a map "map1"
    // map[String]string tells that the map1 maps a String key to a String value
    //Each key-value pair is inside the curly braces {}
    // Each key-value pair is separated by a comma
    
   var map1 = map[string]string{
    "Data Structure and Algorithm" :"Prof. A", 
    "Operating System" :"Prof. B", 
    "Database Management System" :"Prof. C", 
    "Computer Networks" :"Prof. D", 
    "Object Oriented Programming" :"Prof. E", 
   } 
   
   // Output of the map
   // The output is not in the same order as the input
   // because a map is an unordered list
   // it does not maintain the order of the input
   
   fmt.Println("contents of map1 is :\n ", map1)
}

Output: 

contents of map1 is :
  map[Computer Networks:Prof. D Data Structure and Algorithm:Prof. A Database Management System:Prof. C Object Oriented Programming:Prof. E Operating System:Prof. B]

Using := Operator

Syntax:

map_name := map[KeyType]ValueType{key1:value1, key2:value2,...}

Example:

package main
import "fmt"


func main() {
    
    // creating a map "map2"
    // map[String]int tells that the map2 maps a String key to a integer value
    //Each key-value pair is inside the curly braces {}
    // Each key-value pair is separated by a comma
    //using the := operator
    map2 := map[string]int{
    "Anuj" : 1,
    "Kapil" : 2,
    "Sunil" : 3,
    "Jayesh" : 4,
   } 
   
   // Output of the map
   // The output is not in the same order as the input
   // because a map is an unordered list
   // it does not maintain the order of the input
   
   fmt.Println("contents of map2 is :\n ", map2)
}

Output: 

contents of map2 is :
  map[Anuj:1 Jayesh:4 Kapil:2 Sunil:3]

Using the make() Function

We can initialize a map using the built-in make() function. We just need to pass the type of the map to the make() function. The function will return an initialized and ready-to-use map.

Syntax:

make(map[key-type]val-type)

Example:

package main
import ("fmt")


func main() {
 
  // declaring a map "map1"
  map1 := make(map[string]int)
  
  // map before adding anything
  fmt.Println("Content of map before adding anything: ", map1)
  
  //adding key-value pair in map
  map1["Uttar Pradesh"] = 1
  map1["Maharashtra"] = 2
  map1["Delhi"] = 3
  map1["Karnataka"] = 4


  fmt.Println("After adding key-value pairs:",map1)


}

Output: 

Content of map before adding anything:  map[]
After adding key-value pairs: map[Delhi:3 Karnataka:4 Maharashtra:2 Uttar Pradesh:1]

Creating Empty Maps

In order to create an empty Map in the Go language, we can either use the make() function with map type specified or use map initializer with no key: value pairs given.

Example 1: using make()

package main
 
import "fmt"
 
func main() {
    x := make(map[string]string)
    fmt.Println(x)
}

Output: 

map[]

Example 2: using map initializer

package main
 
import "fmt"
 
func main() {
    x := map[string]string{}
    fmt.Println(x)
}

Output: 

map[]

Accessing Elements in a Map

Accessing an element in a map is a very easy task. All you have to do is pass the value of the key using the map name. The value corresponding to that key will be returned.

Syntax: 

Value = map_name[key]

Example: 

package main
import ("fmt")


func main() {
    
    //creating a map
    //map1 maps States and UTs to their capitals
    
    map1:= map[string]string{
      "Jammu and Kashmir" : "Srinagar",
      "Uttar Pradesh" : "Lucknow",
      "Bihar" : "Patna",
      "Madhya Pradesh" : "Bhopal",
      "Tamil Nadu" : "Chennai",
  }
  
  //accessing the value of each key
  //i.e. the capital of each State and UT
  // map1[key]
  
  fmt.Println("The capital of Uttar Pradesh is : ", map1["Uttar Pradesh"])
  fmt.Println("The capital of Madhya Pradesh is : ", map1["Madhya Pradesh"])
  fmt.Println("The capital of Bihar is : ", map1["Bihar"])
  fmt.Println("The capital of Tamil Nadu is : ", map1["Tamil Nadu"])
  fmt.Println("The capital of Jammu and Kashmir is : ", map1["Jammu and Kashmir"])
}

Output: 

The capital of Uttar Pradesh is :  Lucknow
The capital of Madhya Pradesh is :  Bhopal
The capital of Bihar is :  Patna
The capital of Tamil Nadu is :  Chennai
The capital of Jammu and Kashmir is :  Srinagar

Updating and Adding Elements in a Map

Both updating and adding elements in a map can be accomplished by using the variable name of the map, followed by the key value in square brackets [], and the equal (=)operator to set a new value.

Syntax:

Map_name[key] = value

Example 1: adding a new element in a map

package main
import ("fmt")


func main() {
    
    //creating a map
    //map1 maps States and UTs to their capitals
    
    map1:= map[int]string{
      
      1 : "One",
      2 : "Two",
      3 : "Three",
      4 : "Four",
      5 : "Five",
    }
  
   // adding a new element in the map "map1"
   map1[6] = "Six"
   
   // check the elements of the map1
   // to assert that 6: Six has been added
   fmt.Println(map1)
}

Output: 

map[1:One 2:Two 3:Three 4:Four 5:Five 6:Six]

Example 2: updating an element in a map

package main
import ("fmt")


func main() {
    
    //creating a map
    //map1 maps digits to their spellings
    
    map1:= map[int]string{
      
      1 : "One",
      2 : "Two",
      3 : "Three",
      4 : "Four",
      5 : "Five",
    }
  
   //updating 4: Four to 4: Eight
   map1[4] = "Eight"
   
   
   // check the elements of the map1
   // to assert that 4: Four has been updated to 4: Eight
   fmt.Println(map1)
}

Output: 

map[1:One 2:Two 3:Three 4:Eight 5:Five]

Remove an Element From a Map 

The delete() function is used to delete an element from the map.

Syntax:

delete(map_name, key)

Example:

package main
import ("fmt")


func main() {
    
    //creating a map
    //map1 maps numbers to their spellings
    
    map1:= map[int]string{
      
      1 : "One",
      2 : "Two",
      3 : "Three",
      4 : "Four",
      5 : "Five",
    }
  
  // deleting 2: Two
  delete(map1, 2)
  
  //map after the key 2 is deleted
   fmt.Println(map1)
}

Output: 

map[1:One 3:Three 4:Four 5:Five]

Check for a specific element in a map

When the requested key is not present, maps in Go will return a zero value for the map's value type.

Now suppose that a particular key is not at all present in the map. Trying to fetch the value of that key would give zero as the output. It gives a sense that the value of the key is zero, whereas it may be possible that zero is displayed because the key is not present in the map.

Example:

package main
import ("fmt")


func main() {


    map1:= map[string]int{
      
      "one" : 1,
      "two" : 2,
      "three" : 3,
    }
  
  // although the key four is not present 
  // yet the output is 0
 // which is not correct
  fmt.Println(map1["four"])
 
}

 Output:

0

In order to solve this problem, Go also returns a second boolean value. The second boolean value is true if the key is present in the map and it is false if the key is not present in the map.

Example:

package main
import ("fmt")


func main() {


    map1:= map[string]int{
      
      "one" : 1,
      "two" : 2,
      "three" : 3,
    }
  
  // correct way to check existence of an element
  // check for the existence of "four"
  value, isKeyPresent :=map1["four"]
  fmt.Println(value, isKeyPresent) // returns 0 false
  
  //check for the existence of two
  value1, isTwoPresent := map1["two"]
  fmt.Println(value1, isTwoPresent) //returns 2 true
 
}


Output: 

0 false
2 true

Iterating Over Maps

We can iterate over the map using the range keyword. It is used to iterate over a variety of data structures.

Example: 

package main
import ("fmt")


func main() {
    
    // declare and add key-value pairs to the map
    map1:= map[string]int{
      
      "one" : 1,
      "two" : 2,
      "three" : 3,
      "four" : 4,
      "five" : 5,
    }
    
    // use the range keyword to iterate over the map
    // Each iteration returns key and value
    for key, value := range map1{
      
       fmt.Println(key, value)
    }
 
}

Output: 

one 1
two 2
three 3
four 4
five 5

Maps are Reference Types

Internally maps maintain a hash table in order to efficiently store the key-value pair data. In case two map variables refer to the same hash table, changing the content of one variable affects the content of the other.

Example: 

package main
import ("fmt")


func main() {
    
    // declare and add key-value pairs to the map
    map1:= map[string]string{
      
     "India" : "New Delhi",
     "United Kingdom" : "London",
     "Germany" : "Berlin",
     "Japan" : "Tokyo",
     "Netherlands" : "Amsterdam",
    }
    
    // map2 refers to the hash table of map1
    map2 := map1
    
    // map2 contains everything that map1 contained
    fmt.Println("Map2 contents are : \n",map2)
    
    // change the value for Germany using map2
    map2["Germany"] = "London" 
    
    // change is reflected for map1 also 
    fmt.Println("Map1 contents are : \n",map1)
 
}

Output: 

Map2 contents are
 map[Germany:Berlin India:New Delhi Japan:Tokyo Netherlands:Amsterdam United Kingdom:London]
Map1 contents are
 map[Germany:London India:New Delhi Japan:Tokyo Netherlands:Amsterdam United Kingdom:London]

Explanation

It can be seen that when the value for Germany is changed from Berlin to London using map2, the change is also reflected for map1. Therefore we can say that the maps are reference types.

Need For Maps

Maps can be helpful in situations like:

  1. It maps keys to values, resulting in key-value pairs that are a useful way to store data.
  2. Since the keys in the map are unique, searching for a particular key is very fast and one of the vital reasons why we use maps.
  3. Using maps in Go is very easy and simple.

FAQs

  1. How do you create an empty map in Go?
    To make an empty map in Go, we follow the below syntax:
    make(map[key-type]val-type).
     
  2.  How do you access an element in a map in Golang?
    We can simply pass the value of the key using the map name to access an element in a map in Golang.
     
  3. What do you mean by an unordered map in Golang?
    The maps in Golang are unordered, meaning they do not compulsorily maintain the order in which the key-value pairs are added in the map.
     
  4. What is the use of the range keyword in maps in Go?
    We can iterate over the map using the range keyword.
     
  5. How can you remove an element from a map in Go?
    The delete() function is used to delete an element from the map.

Key Takeaways

In this article, we have extensively discussed maps in Go and the various operations involved in the maps.

  •  A map in Go is an unordered collection of key-value pairs. It maps keys to values. The keys are unique within a map, while the values may not be.
  • We can initialize a map using the built-in make() function. We just need to pass the type of the map to the make() function.
  • We can simply pass the value of the key using the map name to access an element in a map in Golang.
  • We can iterate over the map using the range keyword.

We hope that this blog has helped you enhance your knowledge regarding maps in Go and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass