英文:
Why should go method receivers be consistent?
问题
我一直在阅读关于使用指针或值方法接收器的常见问题解答,其中提到:
其次是一致性。如果类型的某些方法必须使用指针接收器,那么其余的方法也应该使用指针接收器,这样无论类型如何使用,方法集都是一致的。
为什么这一点很重要呢?如果我有一些纯粹用于读取数据的方法,我想使用值接收器,以免对接收器进行破坏性更改。这个建议暗示了如果我创建了一个应该修改接收器上的数据的单个方法,我应该将所有的方法都改为使用指针接收器。
有人可以解释一下这个建议背后的原因吗?使用适合工作的正确工具有什么问题吗?
英文:
I've been reading the FAQ re using pointer or value method receivers and it says:
> Next is consistency. If some of the methods of the type must have
> pointer receivers, the rest should too, so the method set is
> consistent regardless of how the type is used.
Why is this important? Surely if I have some methods that are purely for reading data I want to use value receivers so as not to risk making destructive changes to the receiver. This advice suggests that if I then create a single method that should modify data on the receiver I should change all my methods to use pointer receivers.
Can someone explain the reasoning behind this advice? What's wrong with using the right tool for the job?
答案1
得分: 0
这个引用中的关键点是方法集的一致性
。在Go语言中,类型T和*T是不同的类型,它们可能具有不同的方法集(解释也在FAQ中)。
其中一个重要原因是,Go语言中的接口满足是隐式的。因此,如果你的类型的某些方法具有指针接收器,而其他方法没有,这可能导致一种情况,即你期望你的对象满足某个接口,但这取决于你是使用它的指针还是值。
因此,避免这种混淆是一个好的实践。
英文:
The key point in this quote is method set consistency
. Types T and *T are different types in Go and may have different method sets (explanation is also in the FAQ).
One of the reasons it's important, is because interface satisfaction is implicit in Go. So if some of your type's methods have a pointer receiver, while others don't, this can result in a situation, when you expect that your object satisfies some interface, but now that depends on whether you are using it's pointer or value.
So it's good practice to avoid this kind of confusion.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论