why is the capacity of the slice changing? shouldn't it be the same?

Viewed 57

I am fairly new to go and this example has had me baffled:

import "fmt"

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    // Slice the slice to give it zero length.
    s = s[:0]
    printSlice(s)

    // Extend its length.
    s = s[:4]
    printSlice(s)

    // Drop its first two values.
    s = s[2:]
    printSlice(s)
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

output:

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

why does the capacity change to 4 in the last one? capacity by definition is the length of the underlying array.

2 Answers

Slice is built on arrays, it consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).

The key point is segment, not the array.

    s = s[2:]

when you drop the first two values, s became a slice pointed to the other half segment of the array, starting from the third element, so that it's cap is 4.

just like you can not do an s[-1] to point to the previous part of the array, that part can not be count into the cap.

ref: https://blog.golang.org/slices-intro

The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

In your example, in the last case starting element of the slice is 5 and in the underlying arrray({2, 3, 5, 7, 11, 13}) poistion of 5 is 2. To count the capacity you should start counting from index 2. If you count from that position you will get the correct capacity 4

Related