func printSlice(s []int) {
fmt.Printf("%v, len=%d, cap=%d\n",
s, len(s), cap(s))
}
func main() {
fmt.Println("Creating slice")
var s []int // Zero value for slice is nil
for i := 0; i < 10; i++ {
printSlice(s)
s = append(s, 2*i+1)
}
fmt.Println(s)
s1 := []int{2, 4, 6, 8}
printSlice(s1)
s2 := make([]int, 16)
s3 := make([]int, 10, 32)
printSlice(s2)
printSlice(s3)
fmt.Println("Copying slice")
copy(s2, s1)
printSlice(s2)
fmt.Println("Deleting elements from slice")
s2 = append(s2[:3], s2[4:]...)
printSlice(s2)
fmt.Println("Popping from front")
front := s2[0]
s2 = s2[1:]
fmt.Println(front)
printSlice(s2)
fmt.Println("Popping from back")
tail := s2[len(s2)-1]
s2 = s2[:len(s2)-1]
fmt.Println(tail)
printSlice(s2)
}
运行结果:
Creating slice
[], len=0, cap=0
[1], len=1, cap=1
[1 3], len=2, cap=2
[1 3 5], len=3, cap=4
[1 3 5 7], len=4, cap=4
[1 3 5 7 9], len=5, cap=8
[1 3 5 7 9 11], len=6, cap=8
[1 3 5 7 9 11 13], len=7, cap=8
[1 3 5 7 9 11 13 15], len=8, cap=8
[1 3 5 7 9 11 13 15 17], len=9, cap=16
[1 3 5 7 9 11 13 15 17 19]
[2 4 6 8], len=4, cap=4
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0], len=16, cap=16
[0 0 0 0 0 0 0 0 0 0], len=10, cap=32
Copying slice
[2 4 6 8 0 0 0 0 0 0 0 0 0 0 0 0], len=16, cap=16
Deleting elements from slice
[2 4 6 0 0 0 0 0 0 0 0 0 0 0 0], len=15, cap=16
Popping from front
2
[4 6 0 0 0 0 0 0 0 0 0 0 0 0], len=14, cap=15
Popping from back
0
[4 6 0 0 0 0 0 0 0 0 0 0 0], len=13, cap=15
总结:
添加元素时如果超越cap,系统会翻倍分配更大的底层数组