# GO 中常用容器
# 1. 数组
| |
| var classMates [3]string |
| classMates[0] = "小明" |
| classMates[1] = "小红" |
| classMates[2] = "小李" |
| |
| classMates2 := [...]string{"小明","小红","小李"} |
| |
| classMates3 = new([3]string) |
| classMates3[0] = "小明" |
| classMates3[1] = "小红" |
| classMates3[2] = "小李" |
| fmt.Prinrln(*classMates) |
# 2. 切片
可以理解为动态数组,切片的结构体由依稀 3 部分组成
- array 是指向底层存储数据数组的指针
- len 指当前切片的长度,即成员数量
- cap 指当前切片的容量,它总是 >= len
| source := [3]int{1,2,3} |
| sli := source[0:1] |
| len(sli) |
| cap(sli) |
| |
| sli[0] = 4 |
| fmt.Println(source) |
| |
| |
| slice := make([]int,2,4) |
| |
| |
| ex := []int{1,2,3} |
| len(ex) |
| cap(ex) |
动态扩容 append
| |
| arr1 := [...]{1,2,3,4} |
| arr2 := [...]{1,2,3,4} |
| arr3 := [...]{1,2,3,4} |
| |
| |
| sli1 := arr1[0:2] |
| sli2 := arr2[2:4] |
| sli3 := arr3[0:2:2] |
| |
| newSli1 := append(sli1, 5) |
| newSli2 := append(sli2, 5) |
| newSli3 := append(sli3, 5) |
复制切片 copy