This is a creation in Article, where the information may have evolved or changed.
Array
- The array is a value type in the Go language
- Arrays can be compared with = = or! =, but the length of the array is also part of the type, so arrays of different lengths are of different types, as below, this is two different types, because the array length is not the same as the = = or! =
- The following APs and at arrays are of different types
ap:=[5]int{3:2}//下标3的值赋值为2at:=[6]int{}
//数组遍历,i是数组当前下标,p是当前下标对应的值,i可以用_下划线代替,表示忽略as := [3]int{1, 2, 3} for i, p := range as { f.Println(i, "---", p) pa[i] = &as[i] } //还可以常用的遍历循环 le:=len(as) for i:=0;i<le;i++{ f.Println(as[i]) }
- The difference between an array pointer and an array of pointers is no different from C + +.
//指针数组 as := [3]int{1, 2, 3} var pa [3]*int for i, p := range as { f.Println(i, "---", p) pa[i] = &as[i] } //数组指针 var pa2 *[3]int pa2 = &as f.Println(*pa2)
Sliced slice
The slice is not an array, he is a pointer to the underlying array
To create a general make method, the first parameter is a pointer to the array type, the second is the number of elements stored, the third is the storage capacity, if the number of storage exceeds the capacity, then he will allocate memory address (capacity on the original), Len method to obtain the length, the cap gets the capacity
If it is a concise declaration, do not declare that the array length is a slice, for example
s:=[] int{}//切片a:=[10] int{1,2,3,4,5,6,7,8,9,10}//数组c:=a[3,5]//切片c获取数组a下标3到5位元素值,包括3不包括5下标 d:=a[3:]//下标3到a数组的长度
Slice add element, method append
s := make([] int, 5, 10) //第一个参数表示存储类型,第二个表示存储数组长度,第三个是指如果数组最大长度,如果长度超出10,他就会翻倍,分配一个长度20的内存块,如果不设置,最大容量就是数组长度 f.Println(len(s), cap(s)) //获取切片长度和容量 s = append(s, 1, 2, 3, 4, 5, 6)//从尾部添加元素 s=append(s); //可以将一个切片添加到另一个切片中 for _, al := range s { f.Println(al) } //打印结果0 0 0 0 1 2 3 4 5 6 //为什么打印是10个元素呢,因为他的容量是10,所以打印10个元素
Reslice section Reorganization
- The index is slice, the index can not exceed the capacity of the slice slice, the cross-border will not cause the underlying array from the new allocation, but error
a:=[10] int{1,2,3,4,5,6,7,8,9,10}//数组s:=a[3,5]//切片 输出为[4 5]rs:=s[0,1] //reslice 输出为[4],下标从切片s的0开始计算,s的下标0对应的值为4
- If rs:=s[0,10] is an error, because the maximum subscript for the slice S is 7, that is, its capacity is 7, and the capacity is evaluated by: cap (s)