Maps
8 min · Go
Look up values by key with map, Go's dictionary.
Enemy 1 of 5
Key-value lookups with map
This code makes a map that looks up numbers by a name, stores 10 under the key Ada, then prints it. Press Run to see 10.
Why this works
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.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.