I am working on creating a struct that represents a Matrix with methods to manipulate the data within the type. There are two methods that I use as an example to set a single row or column to a specific value. Here is a snippet of my code:
type Matrix struct {
Height, Width int
data [][]int
}
func NewMatrix(nrows, ncols int) (mat *Matrix) {
mat = new(Matrix)
mat.Height = nrows
mat.Width = ncols
mat.data = make([][]int, nrows)
for i := range mat.data {
mat.data[i] = make([]int, ncols)
for j := range mat.data[i]{
mat.data[i][j] = 0
}
}
return
}
func (mat *Matrix) SetCol(col, val int) {
for i := 0; i < mat.Height; i++ {
mat.data[i][col] = val
}
}
func (mat *Matrix) SetRow(row, val int) {
for i := 0; i < mat.Width; i++ {
mat.data[row][i] = val
}
}
When I use this Matrix
type and manipulating the data
attribute like so:
mat := NewMatrix(33,33)
mat.SetCol(2, 3)
mat.SetRow(2, 3)
I am finding that the data
attribute of the Matrix
instance is being set within the method SetCol
but once it returns from this method the data
appears to be the empty matrix that I initialized it to.
Why is the data
attribute that I am manipulating in the method not persisting past the lifetime of the method call? How can I fix this?
Edit
I found out that the issue was that I was instantiating a new instance of a Matrix
on each iteration in a loop which is why the matrix always appeared to be empty after I manipulated it with SetCol
and SetRow
. So the question is not really valid.