Go/複合資料型別/陣列
阿新 • • 發佈:2018-11-16
# 一維陣列的定義與初始化
func test(){
var a [5]int
var a2 [5]int = [5]int{1,2,3,4,5}
a3 := [5]int{1,2,3}
a4 := [5]int{2:2,4:4}
fmt.Println(a)
fmt.Println(a2)
fmt.Println(a3)
fmt.Println(a4)
}
=========
[0 0 0 0 0]
[1 2 3 4 5]
[1 2 3 0 0]
[0 0 2 0 4]
# 二維陣列初始化
func Test(){ var a [3][4]int a1 := [3][4]int{{1,2},{1,2,3,4},{1}} a2 := [3][4]int{1:{1,2}} fmt.Println(a) fmt.Println(a1) fmt.Println(a2) } ========== [[0 0 0 0] [0 0 0 0] [0 0 0 0]] [[1 2 0 0] [1 2 3 4] [1 0 0 0]] [[0 0 0 0] [1 2 0 0] [0 0 0 0]]
# 陣列遍歷
for i := 0; i < len(a2); i++ {
for j := 0; j < len(a2[i]); j++ {
fmt.Print(a2[i][j])
fmt.Print(" ")
}
fmt.Println()
}
# 陣列的賦值與比較
a := [3]int{1,2,3} b := [3]int{1,1,1} var c [3]int = a fmt.Println(a == c) fmt.Println(b == c) =================================== true false
# 陣列作為函式引數是值傳遞 陣列指標傳遞
func test1(a [3]int){
a[0] = 333
fmt.Println(a)
}
func test3(p *[3]int){
(*p)[0]=333
}
a := [3]int{1,2,3}
test1(a)
test3(&a)