Why does this fragment change its capacity?

I am new to golang. Tour of Go has this snippet:

package main

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)
}

and the result:

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]

My confusion is cap=4in the last line - I thought it should stay 6. What is the reason for changing the capacity from 6 to 4 in the last line? In addition, why only the last line changes its capacity, while others do not?

+7
source share
3 answers

Remember that a slice contains data in an array. By removing the first two elements, we moved the beginning of the slice to the right, and now there are fewer slots between the beginning of the slice inside the array and the end of the array.

Removing elements at the end of the slice does not affect the capacity, since the distance between the beginning of the slice inside the array and the end of the auxiliary array does not change.

, .

. Https://blog.golang.org/go-slices-usage-and-internals, .

, ,

func printSlice(s []int) {
    sh := (*reflect.SliceHeader)(unsafe.Pointer(&s))
    fmt.Printf("header=%+v len=%d cap=%d %v\n", sh, len(s), cap(s), s)
}

.

header=&{Data:272990208 Len:6 Cap:6} len=6 cap=6 [2 3 5 7 11 13]
header=&{Data:272990208 Len:0 Cap:6} len=0 cap=6 []
header=&{Data:272990208 Len:4 Cap:6} len=4 cap=6 [2 3 5 7]
header=&{Data:272990216 Len:2 Cap:4} len=2 cap=4 [5 7]
+9

3 : , . ( , ).

, . 0 m (m > 0) N (m < N) , 0 m ( - 0). , N - .

, m (m > 0) k (k < N), m, m k - m N. 0 m . , , /, . , .

+1

This blog clarifies this point by explaining that the array consists of actual values, and the contrasting fragment contains a pointer to an array, more specifically, this pointer points to an array element: "Capacity is the number of elements in the base array ( starting from the element that it points to slice pointer ) "

0
source

Source: https://habr.com/ru/post/1693969/


All Articles