Contents
Dig101: dig more, simplify more, know more.
Slices are everywhere in Go. Unlike fixed-size arrays, a slice is a small header over a variable-length backing array.
0x01 What is a slice?
Runtime definition:
1 | // src/runtime/slice.go |
array points at the backing store; len is length; cap is capacity. Declare a, inspect the header, and print %p for &a, sh, a, and &a[0]:
1 | a := make([]int, 1, 3) |
a and &a[0] match—the slice “value” for printing is the first element’s address. &a, sh, and the header’s storage address match—that is the slice variable on the stack, not the array blob. Keeping those two addresses straight helps with later puzzles.
Side note: what does fmt.Printf("%p", a) do? Chain: fmtPointer → Value.Pointer. For slices, Pointer returns the first element (or 0 if nil)—exactly the data pointer above.
Go passes slices by value (copying the header). For large arrays, passing a slice is far cheaper than copying the array. I covered for-range over big arrays in another Dig101 note (array copies vs slice headers).
Summary: a slice is a header (pointer, len, cap) plus slicing/append ergonomics.
0x02 Can you compare slices?
Only to nil.
1 | s := make([]int, 5) |
Comparing headers is rarely what you want; comparing backing arrays would also need len/cap rules. The language punts.
0x03 Slicing expressions
Form: x[from:high:max]—start at from, length up to high, capacity up to max (each bound must fit the source). Omitted bounds default to x[0:len(x):cap(x)]. Works on arrays too:
1 | s:=make([]int,5) |
With copy/append, see the wiki Slice Tricks. Example—copy without sharing:
b = append(a[:0:0], a...)
Cut/delete with nil slots to drop pointers and avoid leaks:
1 | //Cut |
Worth typing these out until they feel automatic.
0x04 What append does
High level:
- Room in
cap: write afterlenin the same array; return new header with largerlen. - No room: allocate, copy the live prefix, append, return header pointing at the new array.
1 | s := make([]int, 5) |
x and s no longer share storage after growth.
0x05 Compiler lowers for append
The compiler classifies append and rewrites. Besides growslice, three shapes matter:
x = append(y, make([]T, y)...)—memclrfast path for cleared tailx = append(l1, l2...)orappend(slice, string)—memmovefroml2x = append(src, a, b, c)— known argument count → direct stores
From walk.go append (comments abbreviated):
1 | switch { |
Growth policy
At least the requested length n, often double while small.
len < 1024: doublecap- larger: ~1.25× until overflow
- overflow: grow to exact need
- then round through
mallocgcsize classes (betweennand2n)
Extra headroom cuts realloc churn. Size-class rounding is allocator policy (alignment included). Rainy Huang’s Go notes and memory alignment in Go go deeper.
Why uint(n) > uint(cap(s))?
1 | // n is total len after append; cap(s) is int |
Unsigned comparison catches int overflow: a negative n becomes a large uint, forces growslice, which panics on invalid n instead of corrupting memory.
memclrNoHeapPointers vs typedmemclr?
Depends on whether memory is already type-safe and whether T contains pointers.
memclrNoHeapPointers when clearing non-pointer storage that may hold garbage bits before first use.
Otherwise typedmemclr; pointerful types run write barriers for the GC.
See zero initialization vs zeroing, memclrNoHeapPointers, typedmemclr.
Sample code: NewbMiao/Dig101-Go/types/slice
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
