Creating Maps
Start with Creating Maps
You can create maps with literals or with make. A nil map can be read safely but cannot receive a new entry.
What you’ll learn
- Explain the main purpose of creating maps.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use make(map[string]int) for an empty, writable map. A map literal is convenient when starting data is known. Declaring var counts map[string]int without initialization produces a nil map.
Reading a missing key from either a nil or non-nil map returns the value type’s zero value. Writing into a nil map causes a panic. make optionally accepts a capacity hint, but this is not a fixed size or indexable capacity property.
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() {
var missing map[string]int
fmt.Println("Nil map:", missing == nil)
fmt.Println("Nil lookup:", missing["x"])
counts := make(map[string]int)
counts["apple"] = 2
counts["banana"] = 3
fmt.Println("Apple:", counts["apple"])
fmt.Println("Count:", len(counts))
}
Output
Nil map: true
Nil lookup: 0
Apple: 2
Count: 2Trace what the program does
The uninitialized map is nil, and reading "x" returns the zero int value 0. The map created with make is writable, so the two assignments succeed and its length becomes two.
Avoid common mistakes
- Do not assign
m[key] = valuewhile m is nil. - A make capacity hint does not establish a fixed maximum number of map entries.
Try it yourself
Declare a nil map, initialize it with make, and store three item counts. Check len after every insert.
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 Creating 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.