Understanding Golang Maps: [5 Best Examples]

In this tutorial, we will learn about understanding Golang Maps using 5 best examples. Maps in any programming language is a data structure which allows you to store key-value pair as elements to it. We will go through the concept of Map, Hash map, feature of Map using examples in the upcoming sections. so let’s get started.

 

Understanding Golang Maps: [5 Best Examples]

Understanding  Maps

Also read: Golang Arrays vs Slices

Let us first understand what really is Map in programming world. Imagine you have a dictionary where you look up words to find their meanings. In Golang, a Map is similar. It’s like a dictionary that lets you store things (Values) and quickly find them using specific words (Keys). Hence, a Map is a built-in data structure that allows you to store and retrieve values using keys. It is a collection of key-value pairs, where each key is unique and associated with a corresponding value. Maps are useful for storing and managing data that needs to be accessed quickly based on a specific identifier (the Key).

 

Understanding  Hash Map?

The map that is built-in in Go is a hash map. Internally, it is implemented as an array. When you insert a key and value, the key is turned into a number using a hash algorithm. These numbers are not unique for each key. The hash algorithm can turn different keys into the same number. That number is then used as an index into the array. Each element in that array is called a bucket. They key-value pair is then stored in the bucket. If there is already an identical key in the bucket, the previous value is replaced with the new value.

Each bucket is also an array. It can hold more than one value. When two keys map to the the same bucket, that is called collision and the keys and values for both are stored in the bucket.

 

NOTE:

You can use Maps in scenarios where order of the elements does not matter. If order of the elements matter, then you can use Slices.

 

Understanding Golang Maps: [5 Best Examples]

Features of Maps

Also read: What is Race Condition in Golang ? [3 Easy Examples]

  • Maps automatically grow as you add key-value pairs to them.
  • If you know how many key-value pairs you plan to insert into a map, you can use make to create a map with a specific initial size.
  • Passing a map to the len function tells you the number of key-value pairs in a map.
  • The zero value for a map is nil.
  • Maps are not comparable. You can check if they are equal to nil, but you can not check if two maps have identical keys and vales using == or differ using != operator.

 

NOTE:

The key for a map can be any comparable type. This means you can not use a slice or a map as the key for a map.

Reading and Writing Maps

We will understand the read and write operations to a Map using an example as shown below.

Example-1: Demonstrate Read-Write Map

In the below example, we have first declared a Map `numMap` whose key type is integer and value type is string. After declaring a Map, We have added few elements to numMap (write). Lastly we are reading the elements from numMap by printing the elements on standard output.

package main

import "fmt"

func main() {

    //declare a Map
    numMap := map[int]string{}

    //Write to a Map
    numMap[1] = "One"
    numMap[2] = "two"
    numMap[3] = "three"

    //Read from a Map
    fmt.Println("Value for key1 ", numMap[1])
    fmt.Println("Value for key2 ", numMap[2])
    fmt.Println("Value for key3 ", numMap[3])
}
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\Go-Dump> go run .\mapConcept.go
Value for key1 One
Value for key2 two
Value for key3 three

 

The Comma ok Idiom

In Golang, the comma ok idiom is used when we want to differentiate between reading a value and getting back the zero value. Let’s understand this by below example.

Example-2: Demonstrate Empty Key Map

In the above example, We have declared a Map whose key type is string and value type is integer. You can notice that we have not set the key BobID value in the Map but still it returns zero as the output. This works even when there is no existing value associated with the key.  Since we have declared value type as int, therefore it returns zero. Also, we can increment the integer type key value by using the operator ++.

package main

import "fmt"

func main() {

    //declare a Map
    numMap := map[string]int{}

    //Write to a Map
    numMap["AlishID"] = 11
    numMap["SamID"] = 12
    numMap["SmithID"] = 13

    //Read from a Map
    fmt.Println("Alish's ID is ", numMap["AlishID"])
    fmt.Println("Sam's ID is ", numMap["SamID"])
    fmt.Println("Smith's ID is ", numMap["SmithID"])
    fmt.Println("Bob's ID is ", numMap["BobID"])

    numMap["AlishID"]++
    fmt.Println("Alish's new ID is ", numMap["AlishID"])

}
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\Go-Dump> go run .\mapConcept.go
Alish's ID is 11
Sam's ID is 12
Smith's ID is 13
Bob's ID is 0
Alish's new ID is 12

 

As we noticed in the above example that Map returns zero value for the key which is not added in the Map. But what if there is an existing keys whose values are also zero? It will become difficult to find out which key is present in the map and which is not based on the key value Map returns. Hence, comma ok idiom comes in the picture that will tell the difference between a key that is associated with a zero value and a key that is not in the map. Below is the example to demonstrate.

 

Example-3: Demonstrate Ok Idiom

In the above example, we have assigned the results of a map to two variables, value and ok. The first variable gets the output associated with the key and the second variable returns a bool value. If ok is false, the key is not present. If ok is true, the key is present.

package main

import "fmt"

func main() {

    // declare a Map
    numMap := map[string]int{}

    // Write to a Map
    numMap["AlishID"] = 11
    numMap["SamID"] = 12
    numMap["SmithID"] = 13

    value, ok := numMap["AlishID"]
    fmt.Println("Alish's ID is ", v, ok)

    value, ok = numMap["SamID"]
    fmt.Println("Sam's ID is ", v, ok)

    value, ok = numMap["SmithID"]
    fmt.Println("Smith's ID is ", v, ok)

    value, ok = numMap["BobID"]
    fmt.Println("Bob's ID is ", v, ok)
}
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\Go-Dump> go run .\mapConcept.go
Alish's ID is 11 true
Sam's ID is 12 true
Smith's ID is 13 true
Bob's ID is 0 false

 

Deleting From Maps

We can delete the key-value pairs from a Map using a built-in function called delete. Below is the example to delete a key-value pair from a Map.

Example-4: Demonstrate Key Delete in Map

In the below example, delete function takes a map and a key as argument. It removes the key-value pair with the specified key. If the key is not present  in the map or if the Map is nil, nothing will happen. The delete function does not return a value.

package main

import "fmt"

func main() {

    // declare a Map
    numMap := map[string]int{}

    // Write to a Map
    numMap["AlishID"] = 11
    numMap["SamID"] = 12
    numMap["SmithID"] = 13

    fmt.Println("Elements in Map before delete operation: ", numMap)
    delete(numMap, "AlishID")

    fmt.Println("Elements in Map after delete operation: ", numMap, "\n")
}
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\Go-Dump> go run .\mapConcept.go
Elements in Map before delete operation: map[AlishID:11 SamID:12 SmithID:13]
Elements in Map after delete operation: map[SamID:12 SmithID:13]

 

Using Maps as Sets

As we know, a set is a data type that ensures there is at most one of a value, but does not guarantee that the values are in any particular order. Golang does not include a set, but we can use a Map instead to simulate some of its feature. We can use the key of the Map for the type that we want to put into the set and use a bool for the value. Below example demonstrate the concept.

Example-5: Demonstrate Map as Set

In the below example, we have created a Map  whose keys type are integer and values type are bool. We iterate over the elements using a for-range loop to place them into set, associating each int value with the boolean value true. You can notice that we have added 10 values to numSet but the length of numSet is 7. This is because duplicate keys are not allowed in a Map.

package main

import "fmt"

func main() {

    set := map[int]bool{}
    elements := []int{2, 3, 6, 3, 3, 5, 8, 7, 7, 10}

    for _, val := range elements {
        set[val] = true
    }

    fmt.Println(len(elements), len(set))
    fmt.Println(set[4])
    fmt.Println(set[400])

    if set[10] {

        fmt.Println("10 is in the set")
    }
}
OUTPUT
PS C:\Users\linuxnasa\OneDrive\Desktop\Go-Dump> go run .\mapConcept.go
10 7
false
false
10 is in the set

 

Summary

Maps are really useful for keeping track of stuff and quickly finding what you are looking for. They work like a dictionary where you connect words(keys) to meanings (values), making it easier to manage information in your Go programs.

 

Leave a Comment