Understanding Slice Capacity in Go: Difference in Capacity Expansion for int and int8 Slices when Appending Elements

Use this category to discuss the doubts and questions related to the topic Golang on KodeKloud
Hey everyone! I have a question related to slices in Go. Can anyone explain why, when appending an element to a slice of type int that has length and capacity of 3, the capacity gets doubled to 6

slice := make([]int, 2, 3)
fmt.Printf("Type: %T, Value: %v, Length: %d, Capacity: %d\n", slice, slice, len(slice), cap(slice))
//OUTPUT:  Type: []int, Value: [0 0], Length: 2, Capacity: 3
slice = append(slice, 2, 5)
fmt.Printf("Type: %T, Value: %v, Length: %d, Capacity: %d\n", slice, slice, len(slice), cap(slice))
//OUTPUT:  Type: []int, Value: [0 0 2 5], Length: 4, Capacity: 6

but when the slice is of type int8, the capacity after appending the new element becomes 8?

capSlice := make([]int8, 2, 3)
fmt.Printf("Type: %T, Value: %v, Length: %d, Capacity: %d\n", capSlice, capSlice, len(capSlice), cap(capSlice))
//OUTPUT:  Type: []int8, Value: [0 0], Length: 2, Capacity: 3
capSlice = append(capSlice, 2, 5)
fmt.Printf("Type: %T, Value: %v, Length: %d, Capacity: %d\n", capSlice, capSlice, len(capSlice), cap(capSlice))
//OUTPUT:  Type: []int8, Value: [0 0 2 5], Length: 4, Capacity: 8

Thanks in advance for your insights!

Hi @Molham-Al-Nasr,

Please refer to this discussion

1 Like

There is quite a complicated algorithm behind slice reallocation once you exceed capacity. Contrary to what the course video says, it doesn’t always double the capacity when the slice needs to be grown.

1 Like

Hi @Molham-Al-Nasr

I have now produced a detailed write-up on how slices work.

1 Like