Latest web development tutorials

Go Language multidimensional array

Go language array Go language array

Go language support multidimensional arrays, the following common ways multidimensional array declaration:

var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type

The following example declares a three-dimensional array of integers:

var threedim [5][10][4]int

Two-dimensional array

Two-dimensional array is the simplest multi-dimensional arrays, two-dimensional array is essentially a one-dimensional array of. Two-dimensional array is defined as follows:

var arrayName [ x ][ y ] variable_type

variable_type data type Go language, arrayName array name, can be considered a two-dimensional array form, x row, y columns, the following figure illustrates a two-dimensional array of three rows and four columns a:

Two-dimensional array elements can be accessed through a [i] [j].


Two-dimensional array initialization

Multi-dimensional arrays may be the initial value by braces. The following example is a two-dimensional array of 3 rows and four columns:

a = [3][4]int{  
 {0, 1, 2, 3} ,   /*  第一行索引为 0 */
 {4, 5, 6, 7} ,   /*  第二行索引为 1 */
 {8, 9, 10, 11}   /*  第三行索引为 2 */
}

Access dimensional array

Two-dimensional array accessed by specifying the coordinates. As the array row index and column index, for example:

int val = a[2][3]

The above examples visited the fourth element of the third row of two-dimensional array val.

Two-dimensional array can be used to output the nested loop elements:

package main

import "fmt"

func main() {
   /* 数组 - 5 行 2 列*/
   var a = [5][2]int{ {0,0}, {1,2}, {2,4}, {3,6},{4,8}}
   var i, j int

   /* 输出数组元素 */
   for  i = 0; i < 5; i++ {
      for j = 0; j < 2; j++ {
         fmt.Printf("a[%d][%d] = %d\n", i,j, a[i][j] )
      }
   }
}

Run the above example output is:

a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8

Go language array Go language array