Slice Pointer Behavior

What behavior creates a slice from a slice? When you have a slice defined as follows:

s := []int{2, 3, 5, 7, 11, 13}

And you want to change your fragment as follows:

s = s[:3]
// s = [2 3 5]
s = s[:cap(s)]
// s = [2 3 5 7 11 13]

In fact, this works to “expand” your fragment. What does not work:

s = s[2:]
// s = [5 7 11 13]
s = [:cap(s)]
// s = [5 7 11 13]

Thus, you cannot “save” the first two elements in this case, when you created a new slice. Even if the underlying array has not changed, you cannot change the pointer to the beginning of this array, right? Why is this?

-2
source share
1 answer

As @JimB noted in the comments, this is due to the way slices functions in Go.

, , 3 : , , " " ( ). .

s[:x], , , . , , , .

s[x:], . "" , , slice , .

, s := []int{2, 3, 5, 7, 11, 13}, :

ptr: 0x00000000
len: 6
cap: 6

s = s[:3], :

ptr: 0x00000000
len: 3
cap: 6

, len. s = s[:cap(s)], , , , . "", , :

ptr: 0x00000000
len: 6
cap: 6

, s = s[2:], :

ptr: 0x00000010
len: 4
cap: 4

, 16 ( int 64- ), , 4 "", .

, ! , , . reset , , . , Go , , ++.

, s = s[:cap(s)] () , . s = s[:6], , , s = s[:4], ( , , ).

Go ( ), , , , , . . , 33% (, , ), , , @JimB, , , , .

+1

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


All Articles