#Difference between `Struct{}` and `&Struct{}`
6 messages · Page 1 of 1 (latest)
somewhere in the heap.
where ts := Test{name:"Foo"} trasnlate to maybe in the heap.
i'm not sure how to answer this.
but in method receiver, both are exactly the same.
Depends on what you want. The latter is allocated on the heap, the former is allocated on the stack.
They're also not exactly the same when used as a method receiver. You can only modify the values of a receiver when you use a pointer receiver, otherwise you're working with a "read-only" method.
Defaulting to writing everything with pointer receivers isn't a bad practice. Somehow it's always what I end up doing anyway.
func (tp *Test) this part is different. *Test means you the method can modify the value. but whether you allocate it in the heap or (maybe) in the stack
ts := Test{name:"Foo"} //this
ts := &Test{name:"Foo"} //or this
if you use func (tp *Test), the method will be able to modify the value.