我有一个像矩阵的小类
type mat struct {
width, height int
data []float64
}
然后我编写了此方法:
func (a mat) alloc () {
a.data = make([]float64, a.width*a.height)
}
当我这样做的时候
var a mat
a.width = 2
a.height = 2
a.alloc()
for i := 0; i < 4; i++ {
a.data[i] = float64(i)
}
它失败,告诉我索引超出范围[0]。
[当我手动执行时,即用a.alloc()
替换a.data = make([]float64, a.width*a.height)
就可以了。
为什么?
PS:这是垃圾收集器吗?
您需要将alloc
方法的接收器类型更改为指针接收器,才能对实际结构进行更改。 Pointer receivers。
以下代码显示了两者之间的区别-
package main
import "fmt"
type mat struct {
width, height int
data []float64
}
func (a mat) alloc() { // value receiver (pass by value), cannot update original struct value
a.data = make([]float64, a.width*a.height) // this a is just a copy of the original struct value
}
func (a *mat) alloc2() { // pointer receiver, can update original struct value
a.data = make([]float64, a.width*a.height)
}
func main() {
var a mat
a.width = 2
a.height = 2
a.alloc2() // a.alloc() will receive a copy of the original struct, and update the `data` for that copy, but the original value of the struct remains unchanged
for i := 0; i < 4; i++ {
a.data[i] = float64(i)
}
for i := 0; i < 4; i++ {
fmt.Println(a.data[i])
}
}