Maps vs Slices
Start with Maps vs Slices
Slices and maps both store collections of values, but they solve different problems. A slice orders elements by numeric position; a map finds values by unique keys.
What you’ll learn
- Explain the main purpose of maps vs slices.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Choose a slice when sequence, order, duplicates or indexed access matters. Choose a map when you need to associate keys with values or quickly test membership. Neither is a universal replacement for the other.
For example, a list of products in shopping-cart order is naturally a slice, while a quantity lookup by product name can be a map. Sometimes a program needs both: a slice to preserve order and a map for quick lookup.
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() {
order := []string{"pen", "book", "pen"}
quantities := make(map[string]int)
for _, item := range order {
quantities[item]++
}
fmt.Println("First item:", order[0])
fmt.Println("Items in order:", order)
fmt.Println("Pen quantity:", quantities["pen"])
fmt.Println("Unique products:", len(quantities))
}
Output
First item: pen
Items in order: [pen book pen]
Pen quantity: 2
Unique products: 2Trace what the program does
The slice keeps three positions, including two occurrences of pen. Iterating over it builds a map that counts pen twice and book once. The final map has two unique keys, even though the slice contains three items.
Avoid common mistakes
- A map cannot represent a guaranteed item sequence by itself.
- A slice can hold duplicates; a map stores at most one value per distinct key.
Try it yourself
Add one more book to the order slice. Predict the order length, the number of unique products and the quantity of book.
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 Maps vs Slices 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.