Go切片的操作

 1 package main
 2 
 3 import "fmt"
 4 
 5 //切片的操作
 6 
 7 func main() {
 8 
 9     //创建slice
10     var s []int  //zero value for slice is nil
11 
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:4
20 
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:16
24 
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:32
28 
29     //复制slice
30     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 16
32 
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 16
36 
37     front := s2[0]
38     s2 = s2[1:]
39     fmt.Println(front)  //2
40     fmt.Println(s2, len(s2), cap(s2))    //[4 6 0 0 0 0 0 0 0 0 0 0 0 0] 14 15
41 
42     tail := s2[len(s2) - 1]
43     s2 = s2[: len(s2) - 1]
44     fmt.Println(tail)  //0
45     fmt.Println(s2, len(s2), cap(s2))   //[4 6 0 0 0 0 0 0 0 0 0 0 0]  13 15
46 
47 }

猜你喜欢

转载自www.cnblogs.com/yuxiaoba/p/9345804.html