Lets say I want to create a two dimensional array that looks like
/* [
[2],
[3,4],
[6,5,7],
[4,1,8,3]
] */
How do can I create it using go?
Typically if I have a 2d array with equal size columns like
/* [4,1,8,1],
[2,1,3,3],
[7,1,4,3]
*/
matrix := make([][]int, 4)
for i := range matrix {
matrix[i] = make([]int, 3)
}
You can create slices of different sizes at matrix[i]
:
matrix := make([][]int, 4)
for i := range matrix {
matrix[i] = make([]int, i+1)
}
For example,
package main
import (
"fmt"
)
func main() {
matrix := make([][]int, 4)
for i := range matrix {
matrix[i] = make([]int, i+1)
}
fmt.Println(matrix)
}
Output:
[[0] [0 0] [0 0 0] [0 0 0 0]]
Or
package main
import (
"fmt"
)
func main() {
matrix := [][]int{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}
fmt.Println(matrix)
}
Output:
[[2] [3 4] [6 5 7] [4 1 8 3]]