Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a `_` receiver on a value (non-pointer) still copy the value?

Tags:

go

My question is whether or not a copy of a value is made when a method is invoked where _ is the receiver.

type Foo struct {
  // Many fields, making a large struct
}

func (_ Foo) Test(v *T) int {
  // Here we can't use the receiver but the method is still needed
}

So I'm wondering if Go implementations will still copy the Foo value when Test() is invoked, even though it's impossible to actually mutate the receiver value.

var f Foo
f.Test() // Is this making a copy?

I would also wonder about the case of a pointer, which is automatically dereferenced by default.

var f = new(Foo)
f.Test() // Is this making a copy?

I tried looking at the assembly, and I think it may be making the copy, but I just don't know enough to be sure.


For details on the situation:

This is an odd case where I can't use a pointer. The code is machine generated and required to cause a type to fulfill an interface while doing some initialization on the v parameter. (The generated code has metadata about the Foo that gets set on v.)

So if I make the receiver a pointer, the interface won't be fulfilled for "value" instances. This method will be invoked once for each instance, and instances can sometimes be large and/or created in great numbers, which is why I would like to avoid an unnecessary copy.

like image 817
Lye Fish Avatar asked Oct 18 '22 15:10

Lye Fish


1 Answers

According to this blog post, the caller allocates stack elements for return values and the callee populates them.

This leads me to believe that the value is copied and then discarded.

That or a specialized callee would have to be generated in the case of _ receiver

like image 152
David Budworth Avatar answered Oct 22 '22 03:10

David Budworth