1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| package main import "fmt" 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) printSlice(s2) s3 := make([]int, 10, 32) 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) } ===================================output=================================== 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 ===================================output===================================
|