Go语言程序的数组初始化
Go语言数组初始化是最基本的编程训练。通过这个例子可以知道多维数组的初始化,需要注意的是格式。
Go语言程序:
// array project main.go package main import ( "fmt" ) const N int = 5 var a = [N + N]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} var b = [N][N]int{{0, 0, 1}, {1, 2, 3}, {2, 4, 6}, {3, 6, 9}, {4, 8, 12}} var c = [N][N][N]int{ { {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 0, 0, 3, 0}, {0, 0, 0, 0, 0}, {5, 0, 0, 0, 0}, }, { {1, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 7, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 5}, }, { {0, 0, 4, 0, 0}, {0, 0, 0, 7, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 9, 0}, }, } func main() { fmt.Println(a) fmt.Println(b) for i := 0; i < N; i++ { fmt.Println(c[i]) } }
程序运行结果:
[1 2 3 4 5 6 7 8 9 0] [[0 0 1 0 0] [1 2 3 0 0] [2 4 6 0 0] [3 6 9 0 0] [4 8 12 0 0]] [[0 1 0 0 0] [0 0 2 0 0] [0 0 0 3 0] [0 0 0 0 0] [5 0 0 0 0]] [[1 0 0 0 0] [0 0 0 0 0] [0 0 7 0 0] [0 0 0 0 0] [0 0 0 0 5]] [[0 0 4 0 0] [0 0 0 7 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 9 0]] [[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]] [[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]
程序说明:(略)