To create a Two Dimensional Array in Go, you can use slices of slices.
In this example,
matrix
with dimensions 3x3.package main
import (
"fmt"
)
func main() {
matrix := make([][]int, 3)
for i := range matrix {
matrix[i] = make([]int, 3)
for j := range matrix[i] {
matrix[i][j] = i + j
}
}
fmt.Println(matrix)
}
[[0 1 2] [1 2 3] [2 3 4]]
In this example,
matrix
with dimensions 2x2.package main
import (
"fmt"
)
func main() {
matrix := make([][]string, 2)
for i := range matrix {
matrix[i] = make([]string, 2)
for j := range matrix[i] {
matrix[i][j] = fmt.Sprintf("Row %d, Column %d", i+1, j+1)
}
}
fmt.Println(matrix)
}
[[Row 1, Column 1 Row 1, Column 2] [Row 2, Column 1 Row 2, Column 2]]
In this tutorial, we learned How to create a Two Dimensional Array in Go language with well detailed examples.