Reputation: 2491
I try to implement an initialization method for my own type. However after calling the method the variable is unchanged in main(). I probably haven't fully understood how slices work, here is my example code
package main
import "fmt"
type test [][]float64
func (p *test) init(m, n int){
tmp := *p
tmp = make(test, m)
for i := 0; i < m; i++ {
tmp[i] = make([]float64, n)
}
}
func main(){
var t test
t.init(10,2)
fmt.Println(t)
}
I was under the impression that the content of the receiver type * can be changed, but this doesn't seem to be the case for slices. So how do I properly bind my initialization function to my type? I am pretty sure that there is an misunderstanding on my side.... I tried several things like
var t *test = new(test)
or
func (p *test) init(m, n int){
tmp := *p
tmp = append(tmp, make(test, m)...)
for i := 0; i < m; i++ {
tmp[i] = append(tmp[i], make([]float64, n)...)
}
}
and so on but all failed..
The only working solution I currently know of is a unbound method which returns the pointer to a fresh slice. This will do for now, but I want to make this a prerequisite in an interface. So how can I bind it?
Upvotes: 2
Views: 223
Reputation: 28355
func (p *test) init(m, n int){
tmp = make(test, m)
for i := 0; i < m; i++ {
tmp[i] = make([]float64, n)
}
*p = tmp
}
You were close. The above does what you want. But there's no reason to avoid a function that returns a fresh slice. That's idiomatic and feels much like writing a constructor in other languages:
func newTest(m, n int) test {
t = make(test, m)
for i := range t {
t[i] = make([]float64, n)
}
return t
}
Upvotes: 8