动态数组就是不指定长度,使其长度自动变化。
// runtime
type slice struct {
array unsafe.Pointer // 指针
len int // 长度
cap int // 容量
}
// 定义数组
arr := []int{1,2,3}
fmt.Println(arr, len(arr), cap(arr))
打印: [1 2 3] 3 3
func main() {
s1 := make([]int, 3) // 创建数组
fmt.Println(s1, len(s1), cap(s1)) // 创建容量
s2 := make([]int, 3, 6)
fmt.Println(s2, len(s2), cap(s2))
}
result:
[0 0 0] 3 3
[0 0 0] 3 6
func main() {
var s1 []int
emptySlice := []int{}
fmt.Printf("len = %d, cap = %d, %#v\n", len(s1), cap(s1), s1)
fmt.Printf("len = %d, cap = %d, %#v\n", len(emptySlice), cap(emptySlice), emptySlice)
}
result:
len = 0, cap = 0, []int(nil)
len = 0, cap = 0, []int{}
// 观察得到: 没有定义初始化空间,地址指向nil
func main() {
data :=[...]int{0,1,2,3,4,5}
slice :=data[1:4:5]
// length = length -start = 4 -1 = 3
// cap = max - start = 5 -1 = 4
fmt.Printf("len = %d, cap = %d, %#v\n", len(slice), cap(slice), slice)
// length = length -start = 1 - 0 =1
// cap = max - start = max(6)- 0 = 6
slice1 :=data[:1]
fmt.Printf("len = %d, cap = %d, %#v\n", len(slice1), cap(slice1), slice1)
// length = length -start = 1- 0 =1
// cap = max - start = max(3)- 0 =3
slice2 :=data[:1:3]
fmt.Printf("len = %d, cap = %d, %#v\n", len(slice2), cap(slice2), slice2)
// length = length -start = 6 -0 =6
// cap = max - start = 6 -0 =6
slice3 :=data[:]
fmt.Printf("len = %d, cap = %d, %#v\n", len(slice3), cap(slice3), slice3)
}
result:
len = 3, cap = 4, []int{1, 2, 3}
len = 1, cap = 6, []int{0}
len = 1, cap = 3, []int{0}
len = 6, cap = 6, []int{0, 1, 2, 3, 4, 5}