0

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?

vildhjarta
  • 574
  • 2
  • 5
  • 16

1 Answers1

3

Rules of slicing is described in the Spec: Slice expressions.

In your example numbers is an array. When you slice an array, the resulting slice's capacity will be the number of elements from the resulting slice's first element till the last element of the array. When you're slicing a slice, the capacity of the result is the number of elements from the first element till the capacity of the original slice.

So numbers2 := numbers[:4], low index is omitted and therefore defaults to 0, so the result will have a capacity of 8 - 0 = 8 (the size of numbers array).

In numbers3 := numbers[1:5], the result will have a capacity of 7, because the first element in the result is at index 1, so 8 - 1 = 7.

In numbers4 := numbers[3:8], the capacity will be 8 - 3 = 5.

Note: This is when you use a "simple" slice expression, that is when you only provide 2 indices in the slice expression (which has the form of a[low : high]). There is also a "full" slice expression which has the form of a[low : high : max], which additionally controls the resulting slice's capacity by setting it to max - low.

See related questions:

Go slices - capacity/length?

Go slice length is capacity -1, why?

Slicing: Out of bounds error in Go

Slices in Go: why does it allow appending more than the capacity allows?

icza
  • 389,944
  • 63
  • 907
  • 827