Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Language Multidimensional Arrays

Go Language Multidimensional Arrays

Go Language ArraysGo Language Arrays

A multidimensional array is an array of arrays; you can think of it as adata tableorMatrix, where each element can be accessed through multiple indices.

Multidimensional arrays in Go can be used to process structured information such as tabular data, matrix operations, or game boards.

Basic concepts

We can draw an analogy from our everyday parking spaces:

Go supports multidimensional arrays; the following are common ways to declare them:

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

Declaration and Initialization:

// Declare a two-dimensional array var arrayName [rows][cols]elementType // Declare and initialize var arrayName [rows][cols]elementType = [rows][cols]elementType{initialValues}

The following example declares a three-dimensional integer array:

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


Two-dimensional array

A two-dimensional array is the simplest kind of multidimensional array; essentially, a 2D array is composed of one-dimensional arrays. A 2D array is defined as follows:

var arrayName [ x ][ y ] variable_type

variable_type is the data type in Go, arrayName is the array name, a two-dimensional array can be thought of as a table, x is the row, and y is the column; the figure below demonstrates a two-dimensional array a with three rows and four columns:

Elements in a two-dimensional array can be accessed through a[ i ][ j ].

Example

package

main

import

"fmt"

func

main

()

{

   

// Step 1: Create the array

    values

:=

[][]

int

{}

   

// Step 2: Use the append() function to add two rows of one-dimensional arrays to the empty 2D array

    row1

:=

[]

int

{

1

,

2

,

3

}

    row2

:=

[]

int

{

4

,

5

,

6

}

    values

=

append

(

values

,

row1

)

    values

=

append

(

values

,

row2

)

   

// Step 3: Display the two rows of data

    fmt

.

Println

(

"Row 1"

)

    fmt

.

Println

(

values

[

0

])

    fmt

.

Println

(

"Row 2"

)

    fmt

.

Println

(

values

[

1

])

   

// Step 4: Access the first element

    fmt

.

Println

(

"The first element is:"

)

    fmt

.

Println

(

values

[

0

][

0

])

}

The above example produces the following output:

Row 1

[1 2 3]

Row 2

[4 5 6]

The first element is:

1


Initializing a two-dimensional array

Multidimensional arrays can be initialized with curly braces. The following example is a 2D array with 3 rows and 4 columns:

a := [3][4]int{  

 {0, 1, 2, 3} ,   /*  第一行索引为 0 */

 {4, 5, 6, 7} ,   /*  第二行索引为 1 */

 {8, 9, 10, 11},   /* 第三行索引为 2 */

}

**Note: *In the code above, the second-to-last line's } must have a comma, because the last line's } cannot stand alone on a line; it can also be written like this:

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

The following example initializes a 2-row, 2-column two-dimensional array:

Example

package

main

import

"fmt"

func

main

()

{

   

// Create a two-dimensional array

    sites

:=

[

2

][

2

]

string

{}

   

// Add elements to the two-dimensional array

    sites

[

0

][

0

]

=

"Google"

    sites

[

0

][

1

]

=

"Runoob"

    sites

[

1

][

0

]

=

"Taobao"

    sites

[

1

][

1

]

=

"Weibo"

   

// Display the result

    fmt

.

Println

(

sites

)

}

The above example produces the following output:

[[Google Runoob] [Taobao Weibo]]


Accessing Two-Dimensional Arrays

Two-dimensional arrays are accessed by specifying coordinates, such as the row index and column index in the array; for example:



val := a[2][3]

或

var value int = a[2][3]



The above example accesses the fourth element of the third row of the 2D array val.

Two-dimensional arrays can use nested loops to output elements:

Example

package

main

import

"fmt"

func

main

()

{

   

/* Array - 5 rows, 2 columns*/

   

var

a

=

[

5

][

2

]

int

{

{

0

,

0

},

{

1

,

2

},

{

2

,

4

},

{

3

,

6

},{

4

,

8

}}

   

var

i

,

j

int

   

/* Output array elements */

   

for

 

i

=

0

;

i

<

5

;

i

++

{

     

for

j

=

0

;

j <

2

;

j

++

{

         fmt

.

Printf

(

"a[%d][%d] = %d\n"

,

i

,

j

,

a

[

i

][

j

]

)

     

}

   

}

}

The above example produces the following output:

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

The following example creates a multidimensional array with a different number of elements in each dimension:

Example

package

main

import

"fmt"

func

main

()

{

   

// Create an empty two-dimensional array

    animals

:=

[][]

string

{}

   

// Create three one-dimensional arrays, each with a different length

    row1

:=

[]

string

{

"fish"

,

"shark"

,

"eel"

}

    row2

:=

[]

string

{

"bird"

}

    row3

:=

[]

string

{

"lizard"

,

"salamander"

}

   

// Use the append() function to add one-dimensional arrays to the two-dimensional array

    animals

=

append

(

animals

,

row1

)

    animals

=

append

(

animals

,

row2

)

    animals

=

append

(

animals

,

row3

)

   

// Loop to output

   

for

i

:=

range

animals

{

        fmt

.

Printf

(

"Row: %v\n"

,

i

)

        fmt

.

Println

(

animals

[

i

])

   

}

}

The above example produces the following output:

Row: 0

[fish shark eel]

Row: 1

[bird]

Row: 2

[lizard salamander]


Accessing and Modifying Array Elements

Accessing elements

Example

package

main

import

"fmt"

func

main

()

{

   

// Create a 3x3 matrix

    matrix

:=

[

3

][

3

]

int

{

       

{

1

,

2

,

3

},

       

{

4

,

5

,

6

},

       

{

7

,

8

,

9

},

   

}

   

   

// Access a single element

    fmt

.

Println

(

"First row, second column:"

,

matrix

[

0

][

1

])

 

// Output: 2

    fmt

.

Println

(

"Third row, third column:"

,

matrix

[

2

][

2

])

// Output: 9

   

   

// Access an entire row

    fmt

.

Println

(

"Second row:"

,

matrix

[

1

])

 

// Output: [4 5 6]

   

   

// Traverse all elements

    fmt

.

Println

(

"\nTraversing all elements:"

)

   

for

i

:=

0

;

i

<

3

;

i

++

{

       

for

j

:=

0

;

j <

3

;

j

++

{

            fmt

.

Printf

(

"matrix[%d][%d] = %d\n"

,

i

,

j

,

matrix

[

i

][

j

])

       

}

   

}

}

: the array index value starts from 0.

Example

package

main

import

"fmt"

func

main

()

{

   

// Create a 2x2 zero-value matrix

   

var

grid

[

2

][

2

]

int

   

    fmt

.

Println

(

"Matrix before modification:"

,

grid

)

   

   

// Modify the element at a specific position

    grid

[

0

][

0

]

=

10

    grid

[

0

][

1

]

=

20

    grid

[

1

][

0

]

=

30

    grid

[

1

][

1

]

=

40

   

    fmt

.

Println

(

"Matrix after modification:"

,

grid

)

   

   

// Modify a row in bulk

    grid

[

0

]

=

[

2

]

int

{

100

,

200

}

    fmt

.

Println

(

"After modifying the first row:"

,

grid

)

}


Three-Dimensional and Higher-Dimensional Arrays

Three-Dimensional Array Example

Example

package

main

import

"fmt"

func

main

()

{

   

// Declare a 2x3x4 three-dimensional array

   

// It can be understood as: 2 planes, each with 3 rows and 4 columns

   

var

cube

[

2

][

3

][

4

]

int

   

   

// Initialize the three-dimensional array

    cube

=

[

2

][

3

][

4

]

int

{

       

{

// The first plane

           

{

1

,

2

,

3

,

4

},

           

{

5

,

6

,

7

,

8

},

           

{

9

,

10

,

11

,

12

},

       

},

       

{

// The second plane

           

{

13

,

14

,

15

,

16

},

           

{

17

,

18

,

19

,

20

},

           

{

21

,

22

,

23

,

24

},

       

},

   

}

   

   

// Access elements of the three-dimensional array

    fmt

.

Println

(

"cube[0][1][2] ="

,

cube

[

0

][

1

][

2

])

 

// Output: 7

    fmt

.

Println

(

"cube[1][2][3] ="

,

cube

[

1

][

2

][

3

])

 

// Output: 24

   

   

// Traverse the three-dimensional array

    fmt

.

Println

(

"\nContents of the three-dimensional array:"

)

   

for

i

:=

0

;

i

<

2

;

i

++

{

        fmt

.

Printf

(

"Plane %d:\n"

,

i

)

       

for

j

:=

0

;

j <

3

;

j

++

{

           

for

k

:=

0

;

k <

4

;

k

++

{

                fmt

.

Printf

(

"%3d "

,

cube

[

i

][

j

][

k

])

           

}

            fmt

.

Println

()

       

}

        fmt

.

Println

()

   

}

}

See the figure below:


Common Operations on Multidimensional Arrays

1. Traversing with range

Example

package

main

import

"fmt"

func

main

()

{

   

// Create a two-dimensional array

    scores

:=

[

3

][

4

]

int

{

       

{

85

,

90

,

78

,

92

},

       

{

88

,

76

,

95

,

89

},

       

{

92

,

85

,

88

,

90

},

   

}

   

    fmt

.

Println

(

"Student Grade Table:"

)

   

   

// Use range to traverse the two-dimensional array

   

for

i

,

row

:=

range

scores

{

        fmt

.

Printf

(

"Student %d's grades: "

,

i

1

)

       

for

j

,

score

:=

range

row

{

            fmt

.

Printf

(

"%d "

,

score

)

           

// If both the index and the value are needed

            _

=

j

// Avoid unused variable warnings

       

}

        fmt

.

Println

()

   

}

   

   

// Only care about the value, not the index

    total

:=

0

    count

:=

0

   

for

_

,

row

:=

range

scores

{

       

for

_

,

score

:=

range

row

{

            total

+=

score

            count

++

       

}

   

}

    fmt

.

Printf

(

"\nAverage score: %.2f\n"

,

float64

(

total

)

/

float64

(

count

))

}

2. Getting the Array Length

Example

package

main

import

"fmt"

func

main

()

{

   

// Create an irregular multidimensional array

    jagged

:=

[

3

][

3

]

int

{

       

{

1

,

2

,

3

},

       

{

4

,

5

},

       

{

6

,

7

,

8

,

9

},

// Note: this will cause a compile error because each row must have the same length

   

}

   

   

// Correct example: get the array dimensions

    matrix

:=

[

4

][

5

]

int

{}

   

   

// Get the number of rows

    rows

:=

len

(

matrix

)

    fmt

.

Println

(

"Number of Rows:"

,

rows

)

 

// Output: 4

   

   

// Get the number of columns in the first row (all rows have the same length)

    cols

:=

len

(

matrix

[

0

])

    fmt

.

Println

(

"Number of Columns:"

,

cols

)

 

// Output: 5

   

   

// Get the total number of elements

    totalElements

:=

rows

cols

    fmt

.

Println

(

"Total number of elements:"

,

totalElements

)

 

// Output: 20

}

3. Array Comparison

Example

package

main

import

"fmt"

func

main

()

{

   

// Create two identical two-dimensional arrays

    a

:=

[

2

][

2

]

int

{{

1

,

2

},

{

3

,

4

}}

    b

:=

[

2

][

2

]

int

{{

1

,

2

},

{

3

,

4

}}

    c

:=

[

2

][

2

]

int

{{

1

,

2

},

{

3

,

5

}}

   

   

// Arrays can be compared directly (only when the dimensions are exactly the same)

    fmt

.

Println

(

"a == b:"

,

a

==

b

)

 

// Output: true

    fmt

.

Println

(

"a == c:"

,

a

==

c

)

 

// Output: false

   

   

// Note: arrays of different dimensions cannot be compared

   

// d := [2][3]int{{1, 2, 3}, {4, 5, 6}}

   

// fmt.Println(a == d) // Compile error: type mismatch

}


Practical Application Scenarios

Scenario 1: Game Board (Tic-Tac-Toe)

Example

package

main

import

"fmt"

func

main

()

{

   

// Initialize a 3x3 tic-tac-toe board

   

var

board

[

3

][

3

]

string

   

   

// Initialize as empty

   

for

i

:=

0

;

i

<

3

;

i

++

{

       

for

j

:=

0

;

j <

3

;

j

++

{

            board

[

i

][

j

]

=

" "

       

}

   

}

   

   

// Simulate a move

    board

[

0

][

0

]

=

"X"

    board

[

1

][

1

]

=

"O"

    board

[

2

][

2

]

=

"X"

   

   

// Print the board

    fmt

.

Println

(

"Tic-Tac-Toe Board:"

)

   

for

i

:=

0

;

i

<

3

;

i

++

{

       

for

j

:=

0

;

j <

3

;

j

++

{

            fmt

.

Printf

(

" %s "

,

board

[

i

][

j

])

           

if

j <

2

{

                fmt

.

Printf

(

"|"

)

           

}

       

}

        fmt

.

Println

()

       

if

i

<

2

{

fmt

.

Println

(

"---+---+---"

)

       

}

   

}

}

Scenario 2: Student Grade Management System

Example

package

main

import

"fmt"

func

main

()

{

   

// Definition: 3 students, each with 4 courses

   

var

grades

[

3

][

4

]

float64

   

   

// Enter student grades

    grades

=

[

3

][

4

]

float64

{

       

{

85

.

5

,

90

.

0

,

78

.

5

,

92

.

0

},

 

// Student 1's grades

       

{

88

.

0

,

76

.

5

,

95

.

0

,

89

.

5

},

 

// Student 2's grades

       

{

92

.

5

,

85

.

0

,

88

.

5

,

90

.

0

},

 

// Student 3's grades

   

}

   

   

// Calculate each student's average score

    fmt

.

Println

(

"Student Grade Statistics:"

)

   

for

i

,

studentGrades

:=

range

grades

{

        sum

:=

0

.

0

       

for

_

,

grade

:=

range

studentGrades

{

            sum

+=

grade

       

}

        average

:=

sum

/

float64

(

len

(

studentGrades

))

        fmt

.

Printf

(

"Student %d: Average = %.2f\n"

,

i

1

,

average

)

   

}

   

   

// Calculate the average score of each course

    fmt

.

Println

(

"\nCourse Averages:"

)

   

for

j

:=

0

;

j <

4

;

j

++

{

        sum

:=

0

.

0

       

for

i

:=

0

;

i

<

3

;

i

++

{

            sum

+=

grades

[

i

][

j

]

       

}

        average

:=

sum

/

3

.

0

        fmt

.

Printf

(

"Course %d: Average = %.2f\n"

,

j

1

,

average

)

   

}

}

Scenario 3: Image Pixel Processing

Example

package

main

import

"fmt"

func

main

()

{

   

// Simulate a simple 3x3 grayscale image

   

// Each pixel value ranges from 0 (black) to 255 (white)

   

var

image

[

3

][

3

]

int

   

   

// Initialize the image (a simple gradient)

   

for

i

:=

0

;

i

<

3

;

i

++

{

       

for

j

:=

0

;

j <

3

;

j

++

{

            image

[

i

][

j

]

=

(

i

j

)

50

       

}

   

}

   

   

// Display the original image

    fmt

.

Println

(

"Original Image:"

)

    displayImage

(

image

)

   

   

// Image processing: increase brightness

    fmt

.

Println

(

"\nImage After Increasing Brightness:"

)

   

for

i

:=

0

;

i

<

3

;

i

++

{

       

for

j

:=

0

;

j <

3

;

j

++

{

           

// Increase brightness, but not beyond 255

            newValue

:=

image

[

i

][

j

]

50

           

if

newValue >

255

{

                newValue

=

255

           

}

            image

[

i

][

j

]

=

newValue

       

}

   

}

    displayImage

(

image

)

}

func

displayImage

(

img

[

3

][

3

]

int

)

{

   

for

i

:=

0

;

i

<

3

;

i

++

{

       

for

j

:=

0

;

j <

3

;

j

++

{

            fmt

.

Printf

(

"%3d "

,

img

[

i

][

j

])

       

}

        fmt

.

Println

()

   

}

}


Considerations and Best Practices

1. Array Length Is Part of the Type

Example

package

main

import

"fmt"

func

main

()

{

   

// These two are different types!

   

var

a

[

2

][

3

]

int

   

var

b

[

3

][

2

]

int

   

   

// The following code will cause a compile error

   

// a = b // Error: type mismatch

   

    fmt

.

Printf

(

"Type of a: %T\n"

,

a

)

 

// [2][3]int

    fmt

.

Printf

(

"Type of b: %T\n"

,

b

)

 

// [3][2]int

}

2. Value Types vs Reference Types

Example

package

main

import

"fmt"

func

main

()

{

   

// Arrays are value types

    original

:=

[

2

][

2

]

int

{{

1

,

2

},

{

3

,

4

}}

   

   

// Assignment creates a copy

   

copy

:=

original

   

   

// Modifying the copy does not affect the original array

   

copy

[

0

][

0

]

=

100

   

    fmt

.

Println

(

"Original array:"

,

original

)

 

// [[1 2] [3 4]]

    fmt

.

Println

(

"Copied array:"

,

copy

)

     

// [[100 2] [3 4]]

   

   

// If you need reference semantics, you can use slices (introduced in a later article)

}

3. Performance considerations


Frequently Asked Questions

Q1: What is the difference between a multidimensional array and a nested slice?

Feature Multidimensional Arrays Nested Slice
Size Fixed, determined at compile time Dynamic, mutable at runtime
Memory Contiguous allocation Possibly non-contiguous
Performance Fast access Slightly slower, with extra overhead
Use Cases Data size is known Data size is variable

Q2: How to create an irregular two-dimensional array?

Go's arrays require every row to have the same length. If you need an irregular structure, you should use slices:

Example

// Use slices to create an irregular structure

irregular

:=

[][]

int

{

   

{

1

,

2

,

3

},

   

{

4

,

5

},

         

// This row has only 2 elements

   

{

6

,

7

,

8

,

9

},

   

// This row has 4 elements

}

Q3: Can a multidimensional array be used as a function parameter?

Yes, but note that arrays are value types, so passing a large array incurs performance overhead:

Example

func

processMatrix

(

matrix

[

3

][

3

]

int

)

[

3

][

3

]

int

{

   

// Process the matrix...

    matrix

[

0

][

0

]

=

100

   

return

matrix

}

// A better approach is to use pointers or slices

func

processMatrixPtr

(

matrix

[

3

][

3

]

int

)

{

    matrix

[

0

][

0

]

=

100

}

Go Language ArraysGo Language Arrays