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!