Golang中Slice的append详解


在Golang语言中,数据类型不多,但是够用,开发项目过程中,Slice属于最常用的数据结构之一,对其原理理解不清楚,很容易会遗留bug,笔者查询了很多博客资料,对Slice的append原理进行一个总结,如果有写的不清楚不明白之处,请多多包涵,并予以指正。

package main

import "fmt"

func main(){


        s := []int{5}

        s = append(s,7)
        fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0])

        s = append(s,9)
        fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0])
        fmt.Println(s)
        x := append(s, 11)
        fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(x) =", &x[0])
        fmt.Println(s)
        fmt.Println(x)
        y := append(s, 12)
        fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(y) =", &y[0])
        fmt.Println(s)
        fmt.Println(y)
}

输出:

cap(s) = 2 ptr(s) = 0xc0420080c0
cap(s) = 4 ptr(s) = 0xc0420122e0
[5 7 9]
cap(s) = 4 ptr(s) = 0xc0420122e0 ptr(x) = 0xc0420122e0
[5 7 9]
[5 7 9 11]
cap(s) = 4 ptr(s) = 0xc0420122e0 ptr(y) = 0xc0420122e0
[5 7 9]
[5 7 9 12]

猜你喜欢

转载自blog.csdn.net/weixin_40592935/article/details/80916521