1 package main
2
3 import "fmt"
4
5 func main() {
6 /*
7 slice := arr[start:end]
8 切片中的数据:[start,end)
9 arr[:end],从头到end
10 arr[start:]从start到末尾
11
12 从已有的数组上,直接创建切片,该切片的底层数组就是当前的数组。
13 长度是从start到end切割的数据量。
14 但是容量从start到数组的末尾。
15 */
16 a := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
17 fmt.Println("----------1.已有数组直接创建切片--------------------")
18 s1 := a[:5]
19 s2 := a[3:8]
20 s3 := a[5:]
21 s4 := a[:]
22 fmt.Println("a:", a) // [1 2 3 4 5 6 7 8 9 10]
23 fmt.Println("s1:", s1) // [1 2 3 4 5]
24 fmt.Println("s2:", s2) // [4 5 6 7 8]
25 fmt.Println("s3:", s3) // [6 7 8 9 10]
26 fmt.Println("s4:", s4) // [1 2 3 4 5 6 7 8 9 10]
27
28 fmt.Printf("%p\n", &a) // 0xc00012c0f0
29 fmt.Printf("%p\n", s1) // 0xc00012c0f0
30
31 fmt.Println("----------2.长度和容量--------------------")
32 fmt.Printf("s1 len:%d,cap:%d\n", len(s1), cap(s1)) // s1 len:5,cap:10
33 fmt.Printf("s2 len:%d,cap:%d\n", len(s2), cap(s2)) // s2 len:5,cap:7
34 fmt.Printf("s3 len:%d,cap:%d\n", len(s3), cap(s3)) // s3 len:5,cap:5
35 fmt.Printf("s4 len:%d,cap:%d\n", len(s4), cap(s4)) // s4 len:10,cap:10
36
37 fmt.Println("----------3.更改数组的内容--------------------")
38 a[4] = 100
39 fmt.Println(a) // [1 2 3 4 100 6 7 8 9 10]
40 fmt.Println(s1) // [1 2 3 4 100]
41 fmt.Println(s2) // [4 100 6 7 8]
42 fmt.Println(s3) // [6 7 8 9 10]
43
44 fmt.Println("----------4.更改切片的内容--------------------")
45 s2[2] = 200
46 fmt.Println(a) // [1 2 3 4 100 200 7 8 9 10]
47 fmt.Println(s1) // [1 2 3 4 100]
48 fmt.Println(s2) // [4 100 200 7 8]
49 fmt.Println(s3) // [200 7 8 9 10]
50
51 fmt.Println("----------4.更改切片的内容--------------------")
52 s1 = append(s1, 1, 1, 1, 1)
53 fmt.Println(a) // [1 2 3 4 100 1 1 1 1 10]
54 fmt.Println(s1) // [1 2 3 4 100 1 1 1 1]
55 fmt.Println(s2) // [4 100 1 1 1]
56 fmt.Println(s3) // [1 1 1 1 10]
57
58 fmt.Println("----------5.添加元素切片扩容--------------------")
59 fmt.Println(len(s1), cap(s1)) // 9 10
60 s1 = append(s1, 2, 2, 2, 2, 2)
61 fmt.Println(a) // [1 2 3 4 100 1 1 1 1 10]
62 fmt.Println(s1) // [1 2 3 4 100 1 1 1 1 2 2 2 2 2]
63 fmt.Println(s2) // [4 100 1 1 1]
64 fmt.Println(s3) // [1 1 1 1 10]
65 fmt.Println(s4) // [1 2 3 4 100 1 1 1 1 10]
66 fmt.Println(len(s1), cap(s1)) // 14 20
67 fmt.Printf("%p\n", s1) // 0xc0000220a0
68 fmt.Printf("%p\n", &a) // 0xc00000e2d0
69 }