多維陣列
多維陣列基本上是包含其他陣列作為元素的陣列。
它表示為 [sizeDim1][sizeDim2]..[sizeLastDim]type
,用對應於維度長度的數字代替 sizeDim
,用多維陣列中的資料型別代替 type
。
例如,[2][3]int
是代表組成的陣列 2 個陣列的 3 INT 型別元素。
它基本上可的矩陣的表示 2 行和 3 列。
因此,如果你需要為 0 年以後的每分鐘儲存一個數字,我們可以製作像 var values := [2017][12][31][24][60]int
這樣的巨大尺寸數字陣列。
要訪問這種陣列,對於最後一個示例,在 19:42 搜尋 2016-01-31 的值,你將訪問 values[2016][0][30][19][42]
(因為**陣列索引從 0 開始,**而不是像 1 天和幾個月一樣)
以下是一些例子:
// Defining a 2d Array to represent a matrix like
// 1 2 3 So with 2 lines and 3 columns;
// 4 5 6
var multiDimArray := [2/*lines*/][3/*columns*/]int{ [3]int{1, 2, 3}, [3]int{4, 5, 6} }
// That can be simplified like this:
var simplified := [2][3]int{{1, 2, 3}, {4, 5, 6}}
// What does it looks like ?
fmt.Println(multiDimArray)
// > [[1 2 3] [4 5 6]]
fmt.Println(multiDimArray[0])
// > [1 2 3] (first line of the array)
fmt.Println(multiDimArray[0][1])
// > 2 (cell of line 0 (the first one), column 1 (the 2nd one))
// We can also define array with as much dimensions as we need
// here, initialized with all zeros
var multiDimArray := [2][4][3][2]string{}
fmt.Println(multiDimArray);
// Yeah, many dimensions stores many data
// > [[[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]]
// [[[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]]
// We can set some values in the array's cells
multiDimArray[0][0][0][0] := "All zero indexes" // Setting the first value
multiDimArray[1][3][2][1] := "All indexes to max" // Setting the value at extreme location
fmt.Println(multiDimArray);
// If we could see in 4 dimensions, maybe we could see the result as a simple format
// > [[[["All zero indexes" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]]
// [[[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" ""]]]
// [[["" ""] ["" ""]] [["" ""] ["" ""]] [["" ""] ["" "All indexes to max"]]]]