Maps in Go

Maps in Go

In this tutorial, we are going to discuss Maps in the Go language. A map is a built-in type in Go that is used to store key-value pairs.

Maps in Go

In the Go language, a map 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.

The strength of a map is its ability to retrieve data quickly based on the key. A key works like an index, pointing to the value you associate with that key.

A map is constructed by using the keyword map followed by the key data type in square brackets [ ], followed by the value data type. The key-value pairs are then placed inside curly braces on either side { }:

map[key]value{}

A map with data looks like this:

map[string]string{"name": "Ashok Kumar", "gender": "male", "age": "30", "location": "Hyderabad"}

In addition to the curly braces, colons throughout the map connect the key-value pairs. The words to the left of the colons are the keys. Keys can be any comparable type in Go, like strings, ints, and so on.

The keys in the example map are:

  • “name”
  • “gender”
  • “age”
  • “location”

The words to the right of the colons are the values. Values can be any data type. The values in the example map are:

  • “Ashok Kumar”
  • “male”
  • “30”
  • “Hyderabad”

Like the other data types, you can store the map inside a variable, and print it out:

package main

import (
    "fmt"
)

func main() {
    empMap := map[string]string{"name": "Ashok Kumar", "gender": "male", "age": "29", "location": "Hyderabad"}
    fmt.Println(empMap)
}

Output

map[age:29 gender:male location:Hyderabad name:Ashok Kumar]

Run in playground

The order of the key-value pairs may have shifted. In Go, the map data type is unordered. Regardless of the order, the key-value pairs will remain intact, enabling you to access data based on their relational meaning.

Accessing Map Items

You can call the values of a map by referencing the related keys. Since maps offer key-value pairs for storing data, they can be essential and valuable items in your Go program.

If you want to isolate an employee’s name, you can do so by calling empMap[“name”]; the variable holding your map and the related key. Let’s print that out

package main

import (
    "fmt"
)

func main() {
    empMap := map[string]string{"name": "Ashok Kumar", "gender": "male", "age": "29", "location": "Hyderabad"}
    fmt.Println(empMap["name"])
}

Output

Ashok Kumar

Run in playground

Adding items to a map

The syntax for adding new items to a map is the same as that of arrays. The program below adds some new employees to the employeeSalary map.

package main

import (
    "fmt"
)

func main() {
    employeeSalary := make(map[string]int)
    employeeSalary["Ashok Kumar"] = 50000
    employeeSalary["Sai"] = 45000
    employeeSalary["Rama"] = 95000
    employeeSalary["Seetha"] = 65000
    fmt.Println("employeeSalary map contents:", employeeSalary)
}

Output

employeeSalary map contents: map[Ashok Kumar:50000 Rama:95000 Sai:45000 Seetha:65000]

Run in playground

It is also possible to initialize a map during the declaration itself.

package main

import (
    "fmt"
)

func main() {
    employeeSalary := map[string]int{"Ashok Kumar": 50000, "Sai": 45000, "Rama": 95000, "Seetha": 65000}
    fmt.Println("employeeSalary map contents:", employeeSalary)
}

Output

employeeSalary map contents: map[Ashok Kumar:50000 Rama:95000 Sai:45000 Seetha:65000]

Run in playground

Only string types don’t need to be keys. All comparable types, such as boolean, integer, float, complex, string, etc., can also be keys. Even user-defined types such as structs can be keys. If you would like to know more about comparable types, please visit here

Zero value of a map

The zero value of a map is nil. If you try to add elements to a nil map, a run-time panic will occur. Hence the map has to be initialized before adding elements.

package main

func main() {
    var employeeSalary map[string]int
    employeeSalary["Ashok Kumar"] = 50000
}

Output

panic: assignment to entry in nil map 
goroutine 1 [running]: 
main.main() 
/tmp/sandbox779080252/prog.go:5 +0x4b

Run in playground

In the above program, employeeSalary is nil, and we are trying to add a new key to the map. The program will panic with errors.

Keys and Values

Unlike some programming languages, Go does not have any convenient functions to list out the keys or values of a map. An example of this would be Python’s .keys() method for dictionaries. It does, however, allow for iteration by using the range operator.

package main

import (
    "fmt"
)

func main() {
    employeeSalary := map[string]int{"Ashok Kumar": 50000, "Sai": 45000, "Rama": 95000, "Seetha": 65000}
    for key, value := range employeeSalary {
        fmt.Println("Key = ", key, ", Value = ", value)
    }
}

Output

Key =  Ashok Kumar , Value =  50000 
Key =  Sai , Value =  45000 
Key =  Rama , Value =  95000 
Key =  Seetha , Value =  65000

When ranging through a map in Go, it’ll return two values. The first value will be the key, and the second value will be the value. Go will create these variables with the correct data type. In this case, the map key was a string. So the key will also be a string, and the value is an integer.

Checking if a key exists

Maps in Go will return the zero value for the map’s value type when the requested key is missing. Because of this, you need an alternative way to differentiate a stored zero versus a missing key.

package main

import (
    "fmt"
)

func main() {
    employeeSalary := map[string]int{"Ashok Kumar": 50000, "Sai": 45000, "Rama": 95000, "Seetha": 65000}
    fmt.Println(employeeSalary["Raju"])
}

Output

0

Even though the key Raju was not in the map, Go still returned the value of 0. This is because the value data type is an int, and because Go has a zero value for all variables, it returns the zero value of 0.

This doesn’t help when we want to find out whether the key actually exists in the map.

For example, we want to know whether a key is present in the employeeSalary map.

package main

import (
    "fmt"
)

func main() {
    employeeSalary := map[string]int{"Ashok Kumar": 50000, "Sai": 45000, "Rama": 95000, "Seetha": 65000}
    value, ok := employeeSalary["Raju"]
    if ok == true {
       fmt.Println(value)
    } else {
       fmt.Println("Key not found")
    }
}

Output

Key not found

Run in playground

Deleting items from a map

The delete(map, key) is the syntax to delete a key from a map. The delete function does not return any value.

package main

import (
    "fmt"
)

func main() {
    employeeSalary := map[string]int{"Ashok Kumar": 50000, "Sai": 45000, "Rama": 95000, "Seetha": 65000, "Raju" : 40000}
    fmt.Println("Map before deletion", employeeSalary)
    delete(employeeSalary, "Raju")
    fmt.Println("Map after deletion", employeeSalary)
}

Output

Map before deletion map[Ashok Kumar:50000 Raju:40000 Rama:95000 Sai:45000 Seetha:65000] 
Map after deletion map[Ashok Kumar:50000 Rama:95000 Sai:45000 Seetha:65000]

If we try to delete a key that is not present in the map, there will be no runtime error.

Length of the map

The length of the map can be determined using the len function.

package main

import (
    "fmt"
)

func main() {
    employeeSalary := map[string]int{"Ashok Kumar": 50000, "Sai": 45000, "Rama": 95000, "Seetha": 65000, "Raju" : 40000}
    fmt.Println("Length of map is : ", len(employeeSalary))
}

Output

Length of map is :  5

Maps in Go

Scroll to top