Map types in Golang

Map types in Golang

soldering.png

What map types exist in Go? What data types can we use as map keys? What about map values? Are different kinds of maps considered distinct types? And what’s the difference between nil and empty maps? Find out in this handy, bite-size tutorial on map types in Golang.

What map types exist in Go?

There’s no specific data type in Golang called map; instead, we use the map keyword to create a map with keys of a certain type, and values of another type (or the same type).

var menu map[string]float64

In this example, we declare a map that has strings for its keys, and float64s for its values. The result is a variable of a very specific type: map[string]float64.

Map types are distinct

As you know, Go is a strongly-typed language, so that means we can only assign things to the menu variable that have exactly the type map[string]float64. We couldn’t, for example, assign it a map[string]int value, or a map[rune]float64. Those are distinct types.

Golang map key types

What types of keys can a map have? Could we, for example, make a map whose keys are slices, or even functions? No, because the keys must be comparable: that is, the == and != operators must be defined for that type.

All the basic types (string, int, and so on) are comparable; so are structs. Functions and slices are not, and nor are maps, so we can’t have a map whose key is another map!

There’s no such restriction on map values; they can be any type. In fact, it’s common to construct maps of string to any to represent trees of arbitrary data.

Nil versus empty maps

Merely declaring the map’s type doesn’t give us a value we can use: we can’t read or write to a nil map. So if we don’t have any values to put in the map yet, we can initialize it with an empty map literal:

menu := map[string]float64{}

Next

This is part 2 of a Golang tutorial series on maps. Check out the other posts in the series:

Now that you know how to choose the right key and value types for your map, how do we actually store and retrieve values in a Go map? Carry on to the next tutorial to find out!

Read more

Storing and retrieving map values

Storing and retrieving map values

Go maps: declaring and initializing

Go maps: declaring and initializing

0