Slices and Maps in Go: Dynamic Lists and Key-Value Lookups
Store growing lists in Go slices with append(), look up values by name with maps, and avoid the nil-map panic.
You'll learn how Go slices hold dynamic lists, why append must be assigned back to your variable, and how maps store key-value pairs safely with the val, ok check. Assumes basic Go variables and loops.
1. Slices: lists that can grow
In Go, an array like [3]string has a fixed length forever—you can never add a 4th item. Because fixed lengths are rarely convenient, Go programmers use slices ([]string, with empty brackets) 99% of the time.
A slice is a dynamic, resizable list:
package main
import "fmt"
func main() {
tasks := []string{"Write code", "Break build"}
tasks = append(tasks, "Blame Monday")
for i, task := range tasks {
fmt.Printf("%d: %s\n", i, task)
}
}0: Write code
1: Break build
2: Blame MondayNotice tasks = append(tasks, "Blame Monday"). You must assign the result back to tasks—when the slice runs out of room, append allocates a bigger backing array and returns the updated slice.
2. Maps: looking things up by name
When you want to look up a score by player name instead of by number 0, 1, 2, use a map (map[KeyType]ValueType):
package main
import "fmt"
func main() {
scores := map[string]int{
"gerald": 12,
"ada": 99,
}
scores["grace"] = 100
fmt.Println("ada:", scores["ada"])
}ada: 99The comma-ok idiom
If you ask a Go map for a key that isn't there (scores["bob"]), Go doesn't crash—it hands back the zero value (0 for int). To tell whether "bob" actually scored 0 or isn't in the map at all, ask for two values:
score, ok := scores["bob"]
if !ok {
fmt.Println("bob is not on the leaderboard")
} else {
fmt.Println("bob:", score)
}bob is not on the leaderboardDelete "gerald" from scores with delete(scores, "gerald"), then check _, ok := scores["gerald"] to verify ok is false.
3. Never write to a nil map
If you declare var m map[string]int with no {} or make(...), the map is nil (empty nothingness). Reading from a nil map is fine, writing to it panics and crashes your program:
var m map[string]int
m["gerald"] = 1 // panic: assignment to entry in nil mapAlways initialize maps with make(map[string]int) or map[string]int{} before adding keys.
Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
panic: assignment to entry in nil map | Wrote to a var m map[...] without initializing | Initialize with make(map[K]V) or map[K]V{} |
append(s, x) evaluated but not used | Forgot s = append(s, x) | Assign the returned slice back to s |
panic: runtime error: index out of range | Indexed s[5] on a slice of length 3 | Check len(s) or loop with range |
Practice
- If
nums := []int{10, 20, 30, 40}, what doesnums[1:3]contain? - What does
scores["missing"]return forscores := map[string]int{}?
Answers:
[20 30](starts at index 1, stops before index 3).0(the zero value ofint).
What you learned
- Slices (
[]T) are dynamic lists; grow them withs = append(s, item)and loop withrange. - Maps (
map[K]V) store key-value pairs; initialize them withmakeor{}before writing. - Use
val, ok := m[key]to distinguish missing keys from zero values.
Video walkthrough
YouTubeClick play to load video (YouTube)