I’ve noticed an unexpected behavior when appending elements to slices of different integer types (int32
and int64
) in Go. Specifically, the initial capacities assigned to these slices appear to differ based on the type, despite appending the same number of elements.
For instance, when I initialize a slice and append an element using the variadic append function, the capacities differ:
s1 := []int64{}
s2 := []int32{}
s1 = append(s1, []int64{0}...) // len:1, cap:1
s2 = append(s2, []int32{0}...) // len:1, cap:2
And similarly, when appending three elements:
s1 = append(s1, []int64{1, 2, 3}...) // len:3, cap:3
s2 = append(s2, []int32{1, 2, 3}...) // len:3, cap:4
However, when I append elements incrementally, both slices exhibit the same growth pattern:
s1 := []int64{}
s2 := []int32{}
s1 = append(s1, 1) // len:1, cap:1
s1 = append(s1, 2) // len:2, cap:2
s1 = append(s1, 3) // len:3 cap:4
s2 = append(s2, 1) // len:1, cap:1
s2 = append(s2, 2) // len:2, cap:2
s2 = append(s2, 3) // len:3 cap:4
Can someone explain why Go’s append function assigns different capacities to slices of different types (int32
vs. int64
) when elements are appended in groups, but not when appended one at a time? Is this behavior documented somewhere, or is it an implementation detail of the runtime?
Андрей Ходько is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.