Skip to content

Go slices and maps explained with examples

October 30, 2026 · 2 min read

A slice is an ordered list that you grow with append and loop over with range. A map stores key-value pairs, which makes it a good fit for counting words.

Example

package main

import (
	"fmt"
	"slices"
)

func main() {
	var words []string
	words = append(words, "latte", "mocha")
	words = append(words, "latte", "drip", "latte")
	fmt.Println(words, len(words))

	counts := map[string]int{}
	for i, w := range words {
		fmt.Println(i, w)
		counts[w]++
	}

	keys := []string{}
	for w := range counts {
		keys = append(keys, w)
	}
	slices.Sort(keys)
	for _, w := range keys {
		fmt.Println(w, counts[w])
	}
}

Output:

Output
[latte mocha latte drip latte] 5
0 latte
1 mocha
2 latte
3 drip
4 latte
drip 1
latte 3
mocha 1

How it works

  • var words []string makes an empty slice (a nil slice), which is ready to use. append adds one or more items at the end.
  • for i, w := range words runs once per element, giving the index and the element. Use _ if you don't need the index.
  • map[string]int{} is an empty map from strings to ints. A missing key gives the zero value, 0, so counts[w]++ works even the first time you see a word.
  • Looping over a map gives keys in random order, and the order changes from run to run. To print in a fixed order, collect the keys into a slice and sort it with slices.Sort.

Common mistakes

Forgetting to store the result of append. append(words, "chai") on its own doesn't compile, because the new slice is thrown away. Write words = append(words, "chai").

Adding to a nil map. var counts map[string]int can be read, but counts["latte"]++ panics with assignment to entry in nil map. Create it with map[string]int{} first.

Takeaway

Grow slices with s = append(s, x), loop with range, and count with m[key]++ on a map you created with map[string]int{}. Sort the keys when you need a stable order.