---
title: "Slices and maps in Go"
slug: "slices-and-maps"
description: "Use slices as lists and maps as lookup tables: append, len, sub-slices, range, missing keys and the ok form. Fix a panic caused by a nil map."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-go/slices-and-maps"
---

# Slices and maps in Go

How do you keep a list or a lookup table in Go?

## Predict

```go
package main

import "fmt"

func main() {
	a := []int{1, 2, 3}
	b := a
	b[0] = 9
	fmt.Println(a[0])
}
```

What does this program print?

- 1
- 9
- [9 2 3]

Answer: 9 — a and b point at the same array, so writing through b changes what a sees.

Output:

```
9
```

Both slices refer to one array, so the write through b shows up in a.

## Slices

A **slice** is a view on an array. It has a length, `len(s)`, and a capacity, `cap(s)`. `append(s, x)` returns a slice that holds the extra element. It may use the same array or a new, larger one, so always keep the result. `s[1:3]` is a sub-slice: it shares the array with `s` and holds elements 1 and 2.

## Build a slice with append

```go
package main

import "fmt"

func main() {
	var s []int
	for i := 1; i <= 5; i++ {
		s = append(s, i*i)
	}
	fmt.Println(s, len(s))
	fmt.Println(s[1:3])
	for i, v := range s {
		fmt.Println(i, v)
	}
}
```

Output:

```
[1 4 9 16 25] 5
[4 9]
0 1
1 4
2 9
3 16
4 25
```

A slice declared with `var s []int` is empty but usable. `range` gives the index and the value of each element.

Playground: https://go.dev/play/p/6rLqavXZQCK

## Maps

A **map** holds key and value pairs. Write `m := map[string]int{"a": 1}` or `make(map[string]int)`. Read with `m["a"]`, write with `m["a"] = 2` and remove with `delete(m, "a")`. A missing key gives the zero value of the value type. To tell a missing key from a stored zero, use `v, ok := m["a"]`.

## Count words with a map

```go
package main

import "fmt"

func main() {
	words := []string{"go", "is", "fun", "go", "go", "is"}
	counts := make(map[string]int)
	for _, w := range words {
		counts[w]++
	}
	fmt.Println(counts["go"], counts["is"], counts["fun"])
	fmt.Println(counts["rust"])
	n, ok := counts["rust"]
	fmt.Println(n, ok)
	delete(counts, "fun")
	fmt.Println(len(counts))
}
```

Output:

```
3 2 1
0
0 false
2
```

`counts[w]++` works on a missing key because it starts from the zero value. Maps are printed by key here, so the output never changes between runs.

Playground: https://go.dev/play/p/uOm9dLV7ao-

## Fix it

```go
package main

import "fmt"

func main() {
	var m map[string]int
	m["a"] = 1
	fmt.Println(m["a"])
}
```

This program panics. What is the bug?

- m is a nil map: it was declared but never created with make
- The key "a" is too short for a map
- A map cannot hold an int

Answer: m is a nil map: it was declared but never created with make — Reading a nil map is fine, but writing to one panics. Create the map first.

Fixed:

```go
package main

import "fmt"

func main() {
	m := make(map[string]int)
	m["a"] = 1
	fmt.Println(m["a"])
}
```

Output:

```
1
```

## Say it back

In your own words: why must you write s = append(s, x) and not just append(s, x)?

Our sentence: `append` returns the slice that now holds the new element, which may be a new array, so you must store the result back or you lose the change.

## Mission (10 min)

Make a slice of five names, append a sixth, print its length, then count how often each first letter appears with a map and print the counts for two letters you pick.

```sh
go run .
```

## Common questions

### What is a slice in Go?

A slice is a descriptor of a segment of an array: it holds a pointer to the array, a length and a capacity. Slices are the usual way to keep a list in Go. Copying a slice variable copies only the descriptor, so both variables see the same elements. That is why a change through one slice can show up in another.

### How do I add an item to a slice in Go?

Call append and assign the result back: s = append(s, x). The function appends the element to the end of the slice and grows the underlying array when it needs more room. Because append returns the slice it built, ignoring the result loses the new element. You can add several values at once by listing them after the slice.

### How do I check if a key exists in a Go map?

Use the two-value form: v, ok := m[key]. The variable ok is true when the key is in the map and false when it is not, in which case v is the zero value of the value type. This tells a missing key apart from a stored zero, which a plain m[key] lookup cannot do.

## Sources

- https://go.dev/blog/slices-intro (read 2026-12-03)
- https://go.dev/blog/maps (read 2026-12-03)
- https://go.dev/ref/spec#Appending_and_copying_slices (read 2026-12-03)

Measured with go1.27.4 darwin/arm64 on 2026-12-03.
