Maps
Start with Go Maps
A map stores values associated with unique keys. It is useful for lookups such as a student name to a score or a product code to its price.
What you’ll learn
- Explain the main purpose of go maps.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The type map[string]int maps string keys to integer values. A map literal can initialize several entries at once. Looking up scores["Maya"] retrieves that key’s value.
Maps are reference-like values: assigning a map variable to another variable does not clone the key-value entries. Map iteration order is unspecified. A map’s keys must have comparable types; slices, maps and functions are not valid ordinary map keys.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
scores := map[string]int{"Maya": 90, "Arun": 85}
fmt.Println("Maya:", scores["Maya"])
alias := scores
alias["Maya"] = 95
fmt.Println("Updated:", scores["Maya"])
fmt.Println("Entries:", len(scores))
}
Output
Maya: 90
Updated: 95
Entries: 2Trace what the program does
The map begins with two keys. Assigning it to alias keeps both variables referring to the same map data, so updating Maya through alias is visible through scores. The number of distinct keys remains two.
Avoid common mistakes
- Map assignment does not independently copy all entries.
- A map does not preserve insertion order or promise a consistent traversal order.
Try it yourself
Add a third student and check the new length. Assign the map to another variable, update a score, and observe the original.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go Maps in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.