All lessons

Maps

8 min · Go

Look up values by key with map — Go's dictionary.

Go · Maps0/5 cleared

Enemy 1 of 5

Key-value lookups with map

Where a slice looks values up by numeric position, a map looks values up by a meaningful key instead — a player's name, an item id. map[string]int describes the type: a map whose keys are strings and whose values are ints. make(map[string]int) creates an empty one, ready to have entries added.

m[key] = value stores an entry, and m[key] reads one back — the same square-bracket syntax you already know from slices, just keyed by something other than a plain integer index. If you read a key that was never stored, Go quietly gives you the zero value for that value type (0 for int, "" for string) instead of crashing, which is worth knowing since a typo'd key won't necessarily produce an obvious error.

Every mainstream language has its own version of this idea — a dict in Python, an object or Map in JavaScript, a Dictionary in C# — because looking things up by a meaningful name rather than position is such a universally common need.

You
Pincer Crab

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10