How Slice Internals Work

Length, Capacity, and Underlying Arrays

Go slices manage dynamic arrays by tracking current length and total capacity, automatically resizing when needed.

Go slices are dynamic views of underlying arrays where len is the current element count and cap is the total allocated array size. The append function adds elements to the slice, automatically allocating a new, larger underlying array and copying data if the current capacity is exceeded.

s := make([]int, 0, 5) // len=0, cap=5
s = append(s, 1)       // len=1, cap=5
s = append(s, 2, 3)    // len=3, cap=5
s = append(s, 4, 5, 6) // len=6, cap=10 (new array allocated)