Detailed explanation of the underlying array of slices

Time:2022-4-12
package main

import "fmt"

func main() {
    s := []int{0,1,2,3,4,5,6,7,8,9}
    s1 := s[1:5]
    fmt. Printf ("s [1] = = >% P, s length = = >% D, s capacity = = >% d \ n", & s [1], len (s), cap (s))
    fmt.Printf("s[2] ==> %p \n",&s[2])
    fmt.Printf("s[3] ==> %p \n",&s[3])
    fmt.Printf("s[4] ==> %p \n",&s[4])
    fmt.Printf("s[5] ==> %p \n",&s[5])
    fmt.Printf("s[6] ==> %p \n",&s[9])
    fmt.Println("--------------------------------------")
    fmt. Length = [S1, P = >, cap = [S1, len = >, length = [S1, P = > (S1, len = >)
    fmt.Printf("s1[1] ==> %p \n",&s1[1])
    fmt.Printf("s1[2] ==> %p \n",&s1[2])
    fmt.Printf("s1[3] ==> %p \n",&s1[3])
    fmt.Println("--------------------------------------")
    s2 := append(s1,10)
    fmt. Printf ("S2 [0] = = >% P, S2 length = = >% D, S2 capacity = = >% d \ n", & S2 [0], len (S2), cap (S2))
    fmt.Printf("s2[4] ==> %p \n",&s2[4])
    fmt.Println("--------------------------------------")
    s3 := append(s2,[]int{11,12,13,14,15}...)
    fmt. Printf ("S3 [0] = = >% P, S3 length = = >% D, S3 capacity = = >% d \ n", & S3 [0], len (S3), cap (S3))
    fmt.Println(s3)
}
S [1] = = > 0xc00014198, s length = = > 10, s capacity = = > 10
s[2] ==> 0xc0000141a0
s[3] ==> 0xc0000141a8
s[4] ==> 0xc0000141b0
s[5] ==> 0xc0000141b8
s[6] ==> 0xc0000141d8
--------------------------------------
S1 [0] = = > 0xc00014198, S1 length = = > 4, S1 capacity = = > 9
s1[1] ==> 0xc0000141a0
s1[2] ==> 0xc0000141a8
s1[3] ==> 0xc0000141b0
--------------------------------------
S2 [0] = = > 0xc00014198, S2 length = = > 5, S2 capacity = = > 9
s2[4] ==> 0xc0000141b8
--------------------------------------
S3 [0] = = > 0xc0000016090 S3 length = = > 10, S3 capacity = = > 18
[1 2 3 4 10 11 12 13 14 15]

1.s1 := s[1:5], this iss1The length of is 4, and the capacity issStarting from 1, the back capacity when we prints1andsFound when the first few element pointers ofs1The pointers to the four elements of are exactlysFrom number one to number four, it can be proveds1andsA common underlying array.

2. At this time, we go tos1Add an element in, print the pointer of the element, and finds2The address of the fourth element of is exactly the same ass1The address of the fifth element of is the same, which proves thats2And the first two slices still share the underlying array.

3. Let’s gos2Add five elements,s2The original length is 5 and the capacity is 9. At this time, adding five elements will lead to automatic capacity expansion. At this time, print the element address of S3. It is found that it is different from the element address of the first three slices, indicating that the memory address has been reallocated after capacity expansion. The capacity of automatic expansion is calculated in the previous article.

This work adoptsCC agreement, reprint must indicate the author and the link to this article