一、创建slice

不需要通过数组,slice 可以直接定义

package main

import "fmt"

func main() {
    var s []int           // Zero value for slice is nil
    fmt.Println(s == nil) // true
}

每个变量一但定义,都有一个初始值(Zero vaule)为nil


还可以在定义的时候,直接赋值

s1 := []int{2, 4, 6, 8}

当知道长度的时候,不知道值,可以用内建函数make

s2 := make([]int, 16)

还可以指定cap

s3 := make([]int, 10, 32) // len=10, cap=32

1.打印查看

查看slice系统是怎么分配 lencap

package main

import "fmt"

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

func main() {
    var s []int

    for i := 0; i < 100; i++ {
        printSlice(s)
        s = append(s, 2*i+1)
    }
    fmt.Println(s)
}
$ go run 07sliceops.go
len=0, cap=0
len=1, cap=1
len=2, cap=2
len=3, cap=4
len=4, cap=4
len=5, cap=8
len=6, cap=8
len=7, cap=8
len=8, cap=8
len=9, cap=16
len=10, cap=16
len=11, cap=16
len=12, cap=16
len=13, cap=16
len=14, cap=16
len=15, cap=16
len=16, cap=16
len=17, cap=32
len=18, cap=32
......

二、拷贝slice

package main

import "fmt"

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

func main() {
    s1 := []int{2, 4, 6, 8}
    s2 := make([]int, 16)

    copy(s2, s1)

    printSlice(s1)
    printSlice(s2)
}

运行输出

$ go run 07sliceops.go
[2 4 6 8], len=4, cap=4
[2 4 6 8 0 0 0 0 0 0 0 0 0 0 0 0], len=16, cap=16

三、删除slice

package main

import "fmt"

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

func main() {
    s1 := []int{2, 4, 6, 8}
    s2 := make([]int, 16)

    copy(s2, s1)

    printSlice(s1)
    printSlice(s2)

    s2 = append(s2[:3], s2[4:]...) // 删除8,相当于就是 [2 4 6] + [0 0 0 ...]
    printSlice(s2)
}

运行输出

$ go run 07sliceops.go
[2 4 6 8], len=4, cap=4
[2 4 6 8 0 0 0 0 0 0 0 0 0 0 0 0], len=16, cap=16
[2 4 6 0 0 0 0 0 0 0 0 0 0 0 0], len=15, cap=16

删除头尾

s2 = s2[1:]
s2 = s2[:len(s2)-1]