i try to build a two dimensionnal array. My code compile but fail on execution with this error :
Create Matrice with heigth of 10 and width of 10
Area length = 10, Area cap = 10
Loop 0
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
Loop 7
Loop 8
Loop 9
panic: runtime error: index out of range
This is my code, The method create, build a array of array like the go doc show. :
// matrice project matrice.go
package matrice
import (
"fmt"
)
type TwoDimensionnalMatrice struct {
col, row int
area [][]int
}
func (m TwoDimensionnalMatrice) Create(x, y int) {
m.col = x
m.row = y
fmt.Printf("Create Matrice with heigth of %d and width of %d
", x, y)
m.area = make([][]int, m.col)
fmt.Printf("Area length = %d, Area cap = %d
", len(m.area), cap(m.area))
for i := range m.area {
fmt.Printf("Loop %d
", i)
m.area[i] = make([]int, m.row, m.row)
}
}
func (m TwoDimensionnalMatrice) Get(row, col int) int {
return m.area[row][col]
}
and the code that call it :
package main
import (
"fmt"
"matrice"
)
func main() {
mat := matrice.TwoDimensionnalMatrice{}
mat.Create(10, 10)
fmt.Printf("%d", mat.Get(5, 5))
}
The receiver for Create()
is a value instead of a pointer which means you're mutating a copy of mat
in your main function rather than mat
itself.
Change:
func (m TwoDimensionnalMatrice) Create(x, y int)
to:
func (m *TwoDimensionnalMatrice) Create(x, y int)
Or more likely, you want a function in matrice
that returns a new matrix rather than initialising an existing one:
func New(x, y int) (*TwoDimensionnalMatrice, error) {
... create a matrix, initialize it, then return it.
}