Does the `_` receiver get a value (not a pointer) to copy the value?

My question is whether a copy of the value is executed when the method is called, 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 am wondering if the Go implementation will still copy the Foo value when Test() called, even if it is not possible to actually change the receiver value.

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

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

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

I tried to take a look at the assembly, and I think it can make a copy, but I just don’t know enough to be sure.


More about the situation:

This is an odd case where I cannot use a pointer. The code is generated by the machine and requires the type to execute the interface when performing some initialization with the parameter v . (The generated code has metadata about Foo , which is set to v .)

Therefore, if I make the pointer a receiver, the interface will not execute for value instances. This method will be called once for each instance, and instances can sometimes be large and / or created in large numbers, so I would like to avoid an unnecessary copy.

+5
source share
1 answer

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

This makes me think that the value is copied and then discarded.

This or specialized call should be generated in case of _-receiver

+3
source

Source: https://habr.com/ru/post/1242807/


All Articles