I have been playing around with methods in Go by building a small linear algebra library, but I have run into a problem with the following piece of code:
package main
import (
"fmt"
)
type Matrix struct {
mat []float64
nR, nC int
}
func (m Matrix) String() string { ... }
// EmptyMatrix initializes a nR*nC matrix to 0
func EmptyMatrix(nR, nC int) Matrix { ... }
// BuildMatrix creates a matrix build by its rows, and returns a Matrix
func BuildMatrix(rows ...[]float64) Matrix { ... }
// Set sets the value of mat[i,j] to val
func (m *Matrix) Set(i, j int, val float64) {
if (i < m.nR) && (j < m.nC) {
m.mat[i*m.nC+j] = val
} else {
panic(fmt.Sprintf("Index (%d,%d) out of range (0:%d,0:%d)",
i, j, m.nR, m.nC))
}
}
func main() {
matA := matrix.BuildMatrix([]float64{2, 3}, []float64{4, -5})
matB := matA
fmt.Println(matA)
matB.Set(1,1,2)
fmt.Println(matA)
fmt.Printf("%p\n%p\n",&matA,&matB)
}
When ran, this is the output:
[ [ 2.00 3.00 ]
[ 4.00 -5.00 ] ]
[ [ 2.00 3.00 ]
[ 4.00 2.00 ] ]
0xc04207c060
0xc04207c090
If I change a value in matB
, the change is mirrored in matA
, which is not what I want. In Python I would have made a deep copy of matA
to start with, but I haven't found any standard Go implementation of Python's copy.deepcopy()
function. How should I go about solving it?
TESTED SOLUTIONS:
Matrix.mat
is indeed a slice, and I should be copying withcopy(matB.mat, matA.mat
. However, this is not the only problem, since it's still doing the same thing.