Maps

3-minute read
Table of Contents

Maps allow us to map items (keys) onto other items (values). We create a make using the syntax:


make(map[keyType]valueType)

Here we create a map of strings onto integers, where the key is the name of the person and the value is their age:

package main

import "fmt"

func main() {
	// create map
	ages := make(map[string]int)

	// set values for keys "John" and "Mark"
	ages["John"] = 13
	ages["Mark"] = 41

	fmt.Println("The age map is:", ages)
	fmt.Println("John is", ages["John"], "years old")
	fmt.Println("Mark is", ages["Mark"], "years old")

	// edit value
	ages["Mark"] = 42
	fmt.Println("Mark is now", ages["Mark"], "years old")
}
age-map.go
Copy
Notice how we use the format:


mapName[key]

to create, edit and access the value of the map at that key.

Accessing a value for a non-existent key

Run the following code:

package main

import "fmt"

func main() {
	hobbies := make(map[string]string)
	hobbies["Dave"] = "swimming"
	hobbies["James"] = "hiking"

	fmt.Println("Dave's hobbies:", hobbies["Dave"])
	fmt.Println("James's hobbies:", hobbies["James"])
	fmt.Println("Sarah's hobbies:", hobbies["Sarah"])
	fmt.Println("Full hobby map:", hobbies)
}
key-no-exist.go
Copy

Because we tried to access the value of a key that was not added to the map, the result is the zero value of the value type (an empty string).

Getting the length of a map

We use the len function to get the number of key-value pairs in a map:

package main

import "fmt"

func main() {
	ages := make(map[string]int)

	ages["John"] = 13
	ages["Mark"] = 41

	fmt.Println("ages:", ages)
	fmt.Println("length:", len(ages))

	ages["Nina"] = 26
	fmt.Println("ages:", ages)
	fmt.Println("length:", len(ages))
}
map-len.go
Copy

There is a second return value that can be used to determine if the value existed. This is helpful if we want to just check for a key, regardless of the value type:

package main

import "fmt"

func main() {
	hobbies := map[string]string{
		"Dave":  "swimming",
		"James": "hiking",
	}

	maryHobby, exists := hobbies["Mary"]
	if exists {
		fmt.Println("found hobby for Mary:", maryHobby)
	}

	daveHobby, exists := hobbies["Dave"]
	if exists {
		fmt.Println("found hobby for Dave:", daveHobby)
	}
}
map-key-exists.go
Copy

Note the inline way to initialize a map above. We use map[keyType]valueType{} and insert key and value in the format key: value, within the curly braces.

Deleting from a map

The builtin delete function is used with the name of the map and the key in order to remove a key-value pair from the map:

package main

import "fmt"

func main() {
	hobbies := make(map[string]string)
	hobbies["Dave"] = "swimming"
	hobbies["James"] = "hiking"

	fmt.Println("Hobby map:", hobbies)

	// delete Dave's hobby
	delete(hobbies, "Dave")
	fmt.Println("New hobby map:", hobbies)

	// clear all hobbies
	clear(hobbies)
	fmt.Println("Cleared map:", hobbies)
}
map-delete.go
Copy

The clear function is used to remove all key-value pairs from the map.

The map package

As with slices, maps have a package that provides useful functions when handling maps:

package main

import (
	"fmt"
	"maps"
)

func main() {
	list1 := map[string]int{
		"eggs":   12,
		"cheese": 1,
	}
	list2 := map[string]int{
		"cheese": 1,
		"eggs":   12,
	}
	list3 := map[string]int{
		"cheese": 1,
		"eggs":   12,
		"butter": 2,
	}

	if maps.Equal(list1, list2) {
		fmt.Println("list 1 and list 2 are the same")
	}
	if maps.Equal(list1, list3) {
		fmt.Println("list 1 and list 3 are the same")
	}
	if maps.Equal(list2, list3) {
		fmt.Println("list 2 and list 3 are the same")
	}
}
maps-package.go
Copy

The Equals function helps us to check if two maps are identical. It is important to note that the order in which we add values to the map does not matter - list 1 and list 2 are identical because they contain the same set of key-value pairs.

Support us via BuyMeACoffee