Go切片基础

 1 package main
 2 
 3 import "fmt"
 4 
 5 //切片(Slice)本身没有数据,是对底层Array的一个view
 6 //不使用指针就可以改数组内容
 7 //slice可以向后扩展,但是不可以向前扩展
 8 //s[i]不可以超越len(s),s[:]向后扩展不可以超越底层数组Cap(s)
 9 //添加元素时如果超越Cap,系统会重新分配更大的底层数组
10 
11 func updateSlice( s []int){  //s不加长度代表切片
12     s[0] = 100
13 }
14 
15 func main() {
16     arr := [...]int{ 0, 1, 2, 3, 4, 5, 6, 7}
17     fmt.Println("arr[2:6] = ", arr[2:6])  //[2 3 4 5]
18     fmt.Println("arr[:6] = ", arr[:6])    //[0 1 2 3 4 5]
19     s1 := arr[2:]
20     fmt.Println("arr[2:] = ", s1)   //[2 3 4 5 6 7]
21     s2 := arr[:]
22     fmt.Println("arr[:] = ", s2)    //[0 1 2 3 4 5 6 7]
23 
24     //修改切边内容
25     updateSlice(s1)
26     fmt.Println(s1)             //[100 3 4 5 6 7]
27     fmt.Println(arr)            //[0 1 100 3 4 5 6 7]
28 
29     updateSlice(s2)
30     fmt.Println(s2)            //[100 1 100 3 4 5 6 7]
31     fmt.Println(arr)           //[100 1 100 3 4 5 6 7]
32 
33     //再次切片
34     s2 = s2[:5]
35     fmt.Println(s2)         //[100 1 100 3 4]
36     s2 = s2[2:]
37     fmt.Println(s2)      //[100 3 4]
38 
39     //slice扩展
40     arr[0], arr[2] = 0, 2  //把值改回去
41     s1 = arr[2:6]
42     s2 = s1[3:5]
43     fmt.Println(s1)  //[2 3 4 5]
44     fmt.Println(s2)  //[5 6]
45     //6在s1中并没有,为什么可以取出来呢?
46     //slice可以向后扩展,但是不可以向前扩展
47     fmt.Printf("len(s1)=%d, cap(s1)=%d\n", len(s1),cap(s1))  //4,6
48     // fmt.Println( s1[3:7]) 出错
49     //fmt.Println( s1[4]) 出错
50     fmt.Printf("len(s2)=%d, cap(s2)=%d\n", len(s2),cap(s2))    //2,3
51 
52     //向slice添加元素
53     fmt.Println(arr)  //[0 1 2 3 4 5 6 7]
54     s3 := append(s2, 10)
55     s4 := append(s3, 11)
56     s5 := append(s4, 12)
57     fmt.Println(s2)   //[5 6]
58     fmt.Println(s3)   //[5 6 10]
59     fmt.Println(s4)   //[5 6 10 11]
60     fmt.Println(s5)   //[5 6 10 11 12]
61     fmt.Println(arr)  //[0 1 2 3 4 5 6 10]  把7改为了10
62 }

猜你喜欢

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