Golang maps: declaring and initializing

Golang Maps

What is a Golang map? Why is it useful? How does it compare to a slice? How do you declare a map? How do you initialize a map in Go? Fear not; all these questions are answered in this friendly introduction to one of Go’s most powerful features.

Call ’em what you like—hashes, dictionaries, associative arrays, or, in the Go language, maps—this kind of data structure is familiar to every programmer:

{
    'eggs': 1.75,
    'bacon': 3.22,
    'sausage': 1.89,
}

What is a Golang map?

The map data type is built into Golang, so we often use it. Essentially, it lets us store some value (like the 1.75 value in the example above) and retrieve it by looking up a key (like eggs).

Why is this useful? Well, another way to store a bunch of related data values would be in a slice:

menu := []float64{1.75, 3.22, 1.89}

This is inconvenient to deal with because we can only retrieve a value by its index (0, 1, 2, 3, etc), or by looking at every value, in turn, to see if it’s the one we want. And we can’t relate the values to other things. For example, which of these values corresponds to the price of eggs? It’s impossible to know.

By contrast, a map lets us take one set of things (eggsbaconsausage), and set up a one-to-one correspondence (a mapping) with another set of things (1.75, 3.22, 1.89). Much more convenient when we want to look up the price of eggs, for example.