LESSON · 1 OF 18

What a map is

What a map is

A map holds key-value pairs and looks a value up by its key. If you know dictionaries from Python or hashes from Ruby, this is Go's version. For DevOps work maps are everywhere - counting things, looking up config, associating a name with a status.

A map type is written map[KeyType]ValueType:

go
var status map[string]int

That is a map from string keys to int values. But this declaration alone gives you a nil map, and a nil map cannot be written to - writing to one panics. So a declared-but-not-created map is not ready to use yet. The next node creates one properly.

The shape to memorise:

  • map[K]V - a map from keys of type K to values of type V
  • a plain var m map[K]V is nil and cannot be written to
Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute