Thus use slice, if we want to implement a function that create a N size matrix
Implement
straight forward
bad memory using, not contiguous matrix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcnewMatrix(s int) [][]int { m := make([][]int, s) // Wrong! // // for _, row := range m { // row = make([]int, s) // } // for i, _ := range m { m[i] = make([]int, s) } return m }
method 2
ensure to get a contiguous matrix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcnewMatrix(s int) [][]int { // allocate the whole space of the matrix spaces := make([]int, s*s)
// create an empty matrix: [[] [] []...] m := make([][]int, s)
// assign spaces to the matrix i, j := 0, 0 for i < s { m[i] = spaces[j : j+s] i++ j += s }
return m }
Generic
more flexiable!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcnewMatrix[Tany](s int) [][]T { // allocate the whole space of the matrix spaces := make([]T, s*s)
// create an empty matrix: [[] [] []...] m := make([][]T, s)
// assign spaces to the matrix i, j := 0, 0 for i < s { m[i] = spaces[j : j+s] i++ j += s }