英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论