Skip to content

Go (Golang) Tutorial 9 - Maps

Published:

In this tutorial, we’ll learn about maps in Go, which are used to efficiently manage collections of key-value pairs.

Understanding Maps in Go

Basic Map Syntax

Here’s how you can declare and initialize a map in Go:

inventory := map[string]int{
    "pens":      100,
    "notebooks": 50,
}

This example initializes a map called inventory with quantities for pens and notebooks.

Alternatively, you can create an empty map and add items to it later.

inventory := map[string]int{}

This will create an empty map with string keys and integer values.

To add items to the map, you can use the following syntax:

inventory["pens"] = 100
inventory["notebooks"] = 50

Accessing Map Values

You can read values from a map using the keys.

quantity := inventory["pens"]
fmt.Println(quantity) // Output will be 100

If the key doesn’t exist, it returns the zero value for the map’s value type.

unknownQuantity := inventory["markers"]
fmt.Println(unknownQuantity) // Output will be 0, since "markers" does not exist

Checking for Key Existence

To check if a key exists in a map, use a two-value assignment. The first variable is the key’s value, and the second is a boolean indicating the key’s existence.

v, ok := inventory["paper clips"]
if ok {
    fmt.Println("The inventory has", v, "paper clips")
} else {
    fmt.Println("Paper clips are not in the inventory")
}

This will print a message based on whether “paper clips” are in the inventory.

Deleting Map Entries

You can remove entries from a map using the delete function:

delete(inventory, "notebooks")

This will remove notebooks from the inventory.

If we now check if notebooks exist in the inventory, it will return false.

_, ok := inventory["notebooks"]
fmt.Println(ok) // Output will be false

Iterating Over Maps

Lets recreate the inventory and add more items to it.

inventory := map[string]int{
    "pens":      100,
    "notebooks": 50,
    "erasers":   30,
}

You can loop through a map using a for loop:

for item, quantity := range inventory {
    fmt.Printf("There are %d %s in the inventory\n", quantity, item)
}

// Output:
// There are 100 pens in the inventory
// There are 50 notebooks in the inventory
// There are 30 erasers in the inventory

This will print each item and its quantity in the inventory.

Comparing Maps

In Go, you cannot directly compare maps using the == operator. The only valid comparison is with nil to check if a map is initialized:

if inventory == nil {
    fmt.Println("The inventory map is not initialized")
}

With Go 1.21, helper functions are available for map operations. For example, you can use these functions to check if two maps have identical keys and values:

import (
    "fmt"
    "maps"
)

func main() {
    inventory1 := map[string]int{
        "pens":      100,
        "notebooks": 50,
        "erasers":   30,
    }

    inventory2 := map[string]int{
        "pens":      100,
        "notebooks": 50,
        "erasers":   30,
    }

    if maps.Equal(inventory1, inventory2) {
        fmt.Println("The inventories are equal.")
    } else {
        fmt.Println("The inventories are not equal.")
    }
}

Emptying a Map

To empty a map, you can use the clear function.

fmt.Println(inventory1) // Output will be map[erasers:30 notebooks:50 pens:100]
clear(inventory1)
fmt.Println(inventory1) // Output will be map[]

This method will result in an empty map.

Conclusion

In this tutorial, we explored how to use maps in Go. We covered how to declare and initialize them, add, access, and remove entries, check if a key exists, and loop through maps. We also looked at some useful helper functions to compare and empty maps.

Full source code can be found here Github