package main import ( "fmt" ) func main() { var arr1 [3]int = [3]int{1, 2, 3} //定義並初始化長度為3的陣列 fmt.Println(arr1) //[1 2 3] arr2 := [...] int {20:-1} //長度為20的陣列,只有最後一個是-1,其他都是0 fmt.Println(arr2) //[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1] arr3 := [3]int{5, 6, 7} //定義並初始化長度為3的陣列 fmt.Println(arr3) //[5 6 7] arr4 := [...]int{1:100, 3:50, 0:200} //指定下標的陣列,一共四個,因為最大是3 fmt.Println(arr4) //[200 100 0 50] var arr5 [3]int //3個int型的陣列,初始值是3個0,陣列“零值”狀態 fmt.Println(arr5) //[0 0 0] //二維陣列 arr6 := [3][4]int{{0,1,2,3},{6,7,9},{6,4,5}} //列印一維陣列長度 fmt.Println(len(arr6)) //3 //列印二維陣列長度 fmt.Println(len(arr6[1])) //4 //列印整個二維陣列 fmt.Println(arr6) //[[0 1 2 3] [6 7 9 0] [6 4 5 0]] arr7 := [...]string{1:"zhangsan", 6:"lisi", 3:"wangwu"} fmt.Printf("%q",arr7) //["" "zhangsan" "" "wangwu" "" "" "lisi"] }
package main import "fmt" func main() { var a = new([5]int) test(a) fmt.Println(a, len(a)) } func test(a *[5]int) { a[1] = 5 } ///&[0 5 0 0 0] 5
package main import "fmt" func main() { a := [...]User{ {0, "User0"}, {8, "User8"}, } b := [...]*User{ {0, "User0"}, {8, "User8"}, } fmt.Println(a, len(a)) fmt.Println(b, len(b)) } type User struct { Id int Name string } //結果 //[{0 User0} {8 User8}] 2 //[0xc042002440 0xc042002460] 2
//for range遍歷 package main import ( "fmt" ) func main() { arr := [...]string{"golang", "php", "java", "python"} for key, val := range arr { //for _, val := range arr { //如果不想利用key,可以用佔位符 fmt.Printf("key=%v, val=%v\n", key, val) } // key=0, val=golang // key=1, val=php // key=2, val=java // key=3, val=python }