1 package main 2 3 import "fmt" 4 5 //切片的操作 6 7 func main() { 8 9 //创建slice10 var s []int //zero value for slice is nil11 12 for i := 0; i < 10; i++ {13 s = append(s, 2 * i + 1)14 }15 fmt.Println(s) //[1 3 5 7 9 11 13 15 17 19]16 17 s1 := []int{ 2, 4, 6, 8}18 fmt.Println(s1) //[2 4 6 8]19 fmt.Printf("cap:%d\n", cap(s1)) //cap:420 21 s2 := make( []int, 16)22 fmt.Println(s2) //[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]23 fmt.Printf("cap:%d\n", cap(s2)) //cap:1624 25 s3 := make( []int, 10, 32) //32设置的是cap值26 fmt.Println(s3) //[0 0 0 0 0 0 0 0 0 0]27 fmt.Printf("cap:%d\n", cap(s3)) //cap:3228 29 //复制slice30 copy(s2, s1)31 fmt.Println(s2,len(s2), cap(s2)) //[2 4 6 8 0 0 0 0 0 0 0 0 0 0 0 0] 16 1632 33 //删除slice中的元素34 s2 = append( s2[:3], s2[4:]...)35 fmt.Println(s2, len(s2), cap(s2)) //[2 4 6 0 0 0 0 0 0 0 0 0 0 0 0] 15 1636 37 front := s2[0]38 s2 = s2[1:]39 fmt.Println(front) //240 fmt.Println(s2, len(s2), cap(s2)) //[4 6 0 0 0 0 0 0 0 0 0 0 0 0] 14 1541 42 tail := s2[len(s2) - 1]43 s2 = s2[: len(s2) - 1]44 fmt.Println(tail) //045 fmt.Println(s2, len(s2), cap(s2)) //[4 6 0 0 0 0 0 0 0 0 0 0 0] 13 1546 47 }