Go

Go Slices and Maps — Append, Length, Capacity, and Lookup

A slice is a list that grows, and a map is a lookup table from a key to a value. This guide runs one program: a slice starts as 1, 2, 3, gains two elements, and reports len 5 cap 6; a map starts with two names, gains a third, loses one, and reports map len 2. The same guide shows why append must be assigned back, why a plain map lookup cannot tell a missing key from a stored zero, why ranging over a map prints in a different order on different runs, and why writing to a nil map panics while reading from one does not.

Written November 11, 2026 · 9 min read

By the end of this guide
  • Slices: a view over an array, with a length and a capacity
  • append returns a new slice — use the return value
  • Maps: insert, delete, and the comma-ok lookup
  • Ranging over a map: the order is randomized

What this guide is

A slice holds a list of values that can grow. A map holds pairs of a key and a value, and finds a value by its key. These are the two containers every Go program uses, and they answer different questions: a slice answers "what is at position i", a map answers "what is the value for this key". This guide runs one program that uses both, and exits with code 0.

The program

Go
package main

import "fmt"

func main() {
    s := []int{1, 2, 3}
    s = append(s, 4, 5)
    fmt.Println("len", len(s), "cap", cap(s), "s", s)
    m := map[string]int{"ana": 30, "bo": 25}
    m["cy"] = 40
    delete(m, "bo")
    fmt.Println("map len", len(m), "ana", m["ana"])
    v, ok := m["bo"]
    fmt.Println("bo present:", ok, "value:", v)
    for k, val := range m {
        fmt.Println(k, val)
    }
}

The exact output:

Output
len 5 cap 6 s [1 2 3 4 5]
map len 2 ana 30
bo present: false value: 0
ana 30
cy 40

Slices: a view over an array, with a length and a capacity

A slice is a view over an array. It has a length, the number of elements it holds, and a capacity, the number of elements in the array behind it. In the program, s starts as the literal []int{1, 2, 3}, so its length is 3 and its capacity is 3. The line s = append(s, 4, 5) adds two elements, and the output confirms the result: length 5, capacity 6, contents [1 2 3 4 5].

The capacity tells the story of what append did. The backing array held 3 elements, so two more did not fit, and the runtime allocated a new, larger backing array, copied the three elements over, and added the two new ones. The observed capacity after that growth is 6. Length is what the program can read and write; capacity is how much room the backing array has before the next growth. A slice created with make([]int, 3, 10) would start with length 3 and capacity 10, and appending up to seven more elements would not allocate at all, but this guide states only what the program above demonstrates: a 3-element literal has capacity 3, and appending two elements past it leaves capacity 6.

append returns a new slice — use the return value

The append line in the program assigns its result back: s = append(s, 4, 5). That assignment is not style. append returns a new slice value, and the old variable is unchanged unless the return value is stored. The classic bug is calling append and throwing the result away, and a second program tested exactly that:

Go
package main

import "fmt"

func main() {
    s := []int{1, 2, 3}
    append(s, 4)
    fmt.Println("len", len(s), "s", s)
}

This program does not compile. The compiler rejects it with:

Output
append(s, 4) (value of type []int) is not used

The discarded return value is a compile error, not a silent bug, so the mistake cannot ship in this form. The rule is still worth stating plainly, because the fix is the same in every case: always write s = append(s, x), never a bare append(s, x).

Key result
append returns a new slice, and discarding that return value is a compile error: append(s, 4) (value of type []int) is not used. Always assign the result back.

Maps: insert, delete, and the comma-ok lookup

A map stores pairs of a key and a value, and finds a value by its key. In the program, m starts as the literal map[string]int{"ana": 30, "bo": 25}. The line m["cy"] = 40 inserts a new pair, and delete(m, "bo") removes one. The output confirms the result: map len 2 ana 30, so the map holds two entries and ana is still 30.

The interesting lookup is the one for a key that is no longer there. The program reads m["bo"] after deleting bo, two ways. The plain lookup would return 0, the zero value for an int, and that is the problem: a plain lookup cannot tell a missing key from a key that genuinely stores 0. The program uses the comma-ok idiom instead:

Go
v, ok := m["bo"]
fmt.Println("bo present:", ok, "value:", v)

The output is bo present: false value: 0. The second value, ok, is false when the key is absent and true when it is present, so the program knows bo is gone instead of guessing from the 0. Use the comma-ok form whenever the answer matters: a plain lookup is fine when the key is known to be there, and it is the wrong tool when absence is a real possibility.

Ranging over a map: the order is randomized

The last loop in the program ranges over the map:

Go
for k, val := range m {
    fmt.Println(k, val)
}

It prints the two remaining pairs, ana 30 and cy 40, in an order that changes from run to run. The Go specification states the rule plainly: the iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. The two runs demonstrate it directly: the same program printed the pairs in opposite orders. Code that ranges over a map and expects a particular order will behave differently on different runs without any error to explain it. When order matters, collect the keys into a slice, sort them, and then look each one up.

Key result
ranging over a map prints the pairs in an order that is not specified and changes between runs. The same program printed ana then cy in one run and cy then ana in another.

Trap: writing to a nil map panics, reading one does not

Trap
A map declared with var m map[string]int and never initialized is nil. Reading from a nil map is safe, and writing to one is a panic, and a third program tested both halves:
Go
package main

import "fmt"

func main() {
    var m map[string]int
    fmt.Println("read nil map:", m["x"])
    m["x"] = 1
    fmt.Println("wrote nil map")
}

The read prints read nil map: 0 and continues. The write panics before the next line runs:

Output
panic: assignment to entry in nil map

The program exits with status 2, and the wrote nil map line never prints. The fix is to initialize the map before writing to it, with a literal as in the main program or with make(map[string]int). A map received from somewhere else deserves the same check a nil slice does: reading is always safe, writing needs a real map behind it.

Key result
reading a nil map returns the zero value, read nil map: 0, while writing to one panics with panic: assignment to entry in nil map and exits with status 2. Initialize with a literal or make before the first write.

Which container for which job

The two containers overlap less than they first appear to, because each one is built around a different question. The table below states the question each one answers, and the program above demonstrates each row.

Job Container Why
Keep values in the order they were added, and grow the list slice Insertion order is preserved, append grows it, and len and cap report size and room
Look a value up by a key map The key finds the value, and the comma-ok idiom reports a missing key
Visit every pair without caring about order map Ranging visits each pair once, in an order the specification leaves unspecified

When the job is a list of scores in the order they were recorded, that is a slice. When the job is an age for each name, that is a map. When the job needs both — the values in arrival order and a lookup by key — keep a slice for the order and a map for the lookup, because neither container supplies the other one's guarantee.

Checklist

  • Before appending, assign the result back: s = append(s, x) — a bare append(s, x) does not compile.
  • Before trusting cap, remember it is the size of the backing array, not the element count: a 3-element literal has capacity 3, and appending two elements past it leaves capacity 6.
  • Before reading a key that may be missing, use the comma-ok idiom: a plain lookup returns the zero value with no way to tell the key was absent.
  • Before ranging over a map and expecting an order, collect and sort the keys: map iteration order is not specified and changes between runs.
  • Before writing to a map, make sure it is not nil: a literal or make initializes it, and writing to a nil map panics.
  • Before deleting a key, note the map shrinks by one: delete(m, "bo") took the map from 3 entries to 2.

Sources

Keep Exploring