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 }