I have already read this blog post. Every explanation is so clear and understandable. And I got the point that how slices are acting when their capacity is increasing. But I have a question about the opposite of this behaviour. How do the slices behave when their capacity is reduced? Considering this example:
var numbers = [8]int{1, 11, 78, 81, 101, 344, 65, 13}
fmt.Printf("len=%d, cap=%d\n", len(numbers), cap(numbers)) // len=8, cap=8
numbers2 := numbers[:4]
fmt.Printf("len=%d, cap=%d\n", len(numbers2), cap(numbers2)) // len=4, cap=8
For numbers2
it is so obvious. The capacity of the newly created array will be set to two folds the number of elements in the new slice. But considering this example its acting differently:
numbers3 := numbers[1:5]
fmt.Printf("len=%d, cap=%d\n", len(numbers3), cap(numbers3)) // len=4, cap=7
numbers4 := numbers[3:8]
fmt.Printf("len=%d, cap=%d\n", len(numbers4), cap(numbers4)) // len=5, cap=5
I was wondering about that what was the point? Is there any proper way of capacity calculation formula like increasing?