1 package main
2
3 import "fmt"
4
5 func main() {
6 /*
7 数组array:
8 存储一组相同数据类型的数据结构。
9 特点:定长
10
11 切片slice:
12 同数组类似,也叫做变长数组或者动态数组。
13 特点:变长
14
15 是一个引用类型的容器,指向了一个底层数组。
16
17 make()
18 func make(t Type, size ...IntegerType) Type
19
20 第一个参数:类型
21 slice,map,chan
22 第二个参数:长度len
23 实际存储元素的数量
24 第三个参数:容量cap
25 最多能够存储的元素的数量
26
27
28 append(),专门用于向切片的尾部追加元素
29 slice = append(slice, elem1, elem2)
30 slice = append(slice, anotherSlice...)
31 */
32
33 // 1.数组
34 arr := [4]int{1, 2, 3, 4} // 定长
35 fmt.Println(arr)
36
37 // 2.切片
38 var s1 []int
39 fmt.Println(s1) // []
40
41 s2 := []int{1, 2, 3, 4} // 变长
42 fmt.Println(s2) // [1 2 3 4]
43 fmt.Printf("%T,%T\n", arr, s2) // [4]int,[]int
44
45 s3 := make([]int, 3, 8)
46 fmt.Println(s3) // [0 0 0]
47 fmt.Printf("容量:%d,长度:%d\n", cap(s3), len(s3)) // 容量:8,长度:3
48 s3[0] = 1
49 s3[1] = 2
50 s3[2] = 3
51 fmt.Println(s3) // [1 2 3]
52 // fmt.Println(s3[3]) //panic: runtime error: index out of range
53
54 // append()
55 s4 := make([]int, 0, 5)
56 fmt.Println(s4) // []
57 s4 = append(s4, 1, 2) //
58 fmt.Println(s4) // [1 2]
59 s4 = append(s4, 3, 4, 5, 6, 7) //
60 fmt.Println(s4) // [1 2 3 4 5 6 7]
61 s4 = append(s4, s3...) //
62 fmt.Println(s4) // [1 2 3 4 5 6 7 1 2 3]
63
64 // 遍历切片
65 for i := 0; i < len(s4); i++ {
66 fmt.Println(s4[i])
67 }
68
69 for i, v := range s4 {
70 fmt.Printf("%d-->%d\n", i, v)
71 }
72
73 }