#Difference between `Struct{}` and `&Struct{}`

6 messages · Page 1 of 1 (latest)

warped wind
#

If the receiver expects a pointer then why does Test{} work the same?
go implicitly take a reference to the value.

#

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.

split pelican
#

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.

warped wind
#

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.