數(shù)組
- 聲明數(shù)組需指定元素類型和元素個數(shù)
func TestArray(t *testing.T){
arr := [3]int{1,2,3}
t.Log(arr)
}
//result : [1,2,3]
- 初始化賦值元素個數(shù)要小于,或等于指定個數(shù)。沒有初始化的元素,默認賦零值
func TestArray(t *testing.T){
arr := [3]int{}
t.Log(arr)
}
//result : [0,0,0]
- 可使用
...忽略設(shè)置元素個數(shù),自動根據(jù)初始化元素分配對應(yīng)長度數(shù)組
func TestArray(t *testing.T){
arr := [...]int{}
arr2 := [...]int{1,0}
t.Log(arr,arr2)
}
//result : [] [1,0]
- 使用
cap(),len()查看數(shù)組大小,go語言數(shù)組不能擴容
func TestArray(t *testing.T){
arr := [...]int{1,0}
t.Log(arr,cap(arr),len(arr))
}
//result : [1 0] 2 2
- 函數(shù)參數(shù)和返回值定義必須指定具體元素個數(shù)
func getLen(arr [...]int) int {
return len(arr)
}
func TestArray(t *testing.T){
arr := [...]int{1,0}
t.Log(getLen(arr))
}
//result : use of [...] array outside of array literal
func getLen(arr [2]int) int {
return len(arr)
}
func TestArray(t *testing.T){
arr := [...]int{1,0}
t.Log(getLen(arr))
}
//result : 2
原因: ... 自動推導(dǎo)個數(shù)必須在編譯時確定,函數(shù)行參無法在編譯時確定元素個數(shù)?
所以Go語言中常用的是函數(shù)傳切片而不是傳數(shù)組
- 支持多維數(shù)組
切片
A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array
- 聲明切片幾種方式
- 直接聲明
func TestSlice(t *testing.T) {
var slice []int
t.Log(reflect.TypeOf(slice))
}
//result : []int
- 聲明并賦字面值
func TestSlice(t *testing.T) {
slice := []int{1,2,3,4}
t.Log(slice)
t.Log(reflect.TypeOf(slice))
}
//result: [1,2,3,4] []int
- 從數(shù)組或切片中切出
func TestSlice(t *testing.T) {
arr := [...]int{1,2,3,4}
slice := arr[0:3]
slice2 := slice[1:2]
t.Log(slice,slice2)
t.Log(reflect.TypeOf(slice),reflect.TypeOf(slice))
}
- 不允許創(chuàng)建容量比長度小的切片
- 切片只有底層數(shù)組有關(guān)
- 使用append增加元素 切片允許擴容
- 指定第三個參數(shù)限制切片容量
- 空切片和nil 切片 if==nil