Search⌘ K

Understanding Maps

Explore how to use maps in Go to efficiently store and retrieve key-value data. Understand declaring maps with make and literals, adding and updating entries, accessing values safely, and iterating with non-deterministic order for effective data handling.

Introduction

Maps are a collection of key-value pairs that a user can use to store some data and retrieve it with a key. In some languages, these are called dictionaries (Python) or hashes (Perl). In contrast to an array/slice, finding an entry in a map requires a single lookup versus iterating over the entire slice comparing values. With a large set of items, this can give us significant time savings.

Declaring a map

There are several ways to declare a map. Let's first look at using make:

Go (1.18.2)
var counters = make(map[string]int, 10)

...