在一个值(非指针)上使用 `_` 接收器,是否仍然会复制该值?

huangapple go评论86阅读模式
英文:

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

问题

我的问题是,当调用一个方法时,是否会对值进行复制,其中 _ 是接收者。

type Foo struct {
  // 许多字段,构成一个大的结构体
}

func (_ Foo) Test(v *T) int {
  // 在这里我们不能使用接收者,但仍然需要这个方法
}

所以我想知道,当调用 Test() 方法时,Go 实现是否仍然会复制 Foo 值,即使实际上无法改变接收者的值。

var f Foo
f.Test() // 这会进行复制吗?

我还想知道指针的情况,因为默认情况下会自动解引用。

var f = new(Foo)
f.Test() // 这会进行复制吗?

我尝试查看汇编代码,我认为可能会进行复制,但我不确定是否足够了解。

英文:

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.

答案1

得分: 3

根据这篇博客文章,调用者为返回值分配栈元素,而被调用者填充这些元素。

这让我相信该值被复制然后丢弃。

要么在 _ receiver 的情况下,需要生成一个专门的被调用者。

英文:

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

huangapple
  • 本文由 发表于 2016年2月12日 04:21:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/35349279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定