liveBook · Manning

Slice length

As explained in 100 Go Mistakes and How to Avoid Them

Slice length is the number of elements currently contained in a Go slice and available through its indices.

A common mistake is to treat a slice’s spare capacity as elements that are already available. A Go slice has a length and a capacity: length counts its current elements; capacity describes space in its backing array. Only elements within the length can be indexed. section 3.4

Allocated does not mean indexable

With `s := make([]int, 3, 6)`, `s` prints as `[0 0 0]`. Assigning `s[1] = 1` works, but `s[4] = 0` panics with “index out of range [4] with length 3.” Use `s = append(s, 2)` to put an element into the spare space; the length then becomes 4. section 3.4

Length also determines how much work `copy` can do: it copies at most the smaller of the source and destination lengths. A destination with spare capacity but zero length receives no elements. Give it sufficient length before copying; pass the destination first. section 3.8

src := []int{0, 1, 2}
var dst []int
copy(dst, src)
fmt.Println(dst)

The nil destination has length zero, so this copy prints `[]`. section 3.8

src := []int{0, 1, 2}
dst := make([]int, len(src))     #1
copy(dst, src)
fmt.Println(dst)

Giving the destination the source’s length lets the copy print `[0 1 2]`. section 3.8

When the result size is known, choose length to match how elements will be added. Use `make([]Bar, 0, n)` with `append`, or `make([]Bar, n)` with indexed assignments. Do not append to the latter expecting to fill its existing slots: it already contains `n` zero-valued elements. If the final count is uncertain, a known upper bound can still be useful as capacity. section 3.5

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains slice backing arrays, index bounds, append behavior, allocation choices, and copy’s length limit without descending into runtime implementation.
Examples
Contrasts a three-length, six-capacity slice with an out-of-range assignment, and a zero-length copy destination with a length-sized one.
What it assumes
Assumes basic Go expression familiarity while defining slice length, capacity, and backing arrays directly.
What you can do after
Diagnose/debug indexing panics and empty copies, then choose a slice length or capacity suited to indexed writes or append.
How it connects
Connects slice length to capacity, backing arrays, append, slice initialization, and copy.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.