英文:
Syntax to use to call methods-on-pointers
问题
一些问题(例如这个问题)遇到了这样的问题:在某些情况下,调用:
obj.method()
如果method
接受对象指针是无效的。但在某些情况下是有效的(例如obj
是变量的情况下)。
问题:为了保持一致性,是否应该始终使用(&obj).method()
?否则,调用相同方法的代码在传递obj
的方式上是不一致的。
英文:
Some questions like this run into problem that in some cases calling:
obj.method()
Is invalid if method
accepts pointer to object. But in some cases it is valid (like if obj
is variable).
Question: should (&obj).method()
always be used for consistency? Otherwise, code for calling same methods on same "type" is inconsistent depending on how obj
was passed.
答案1
得分: 2
不,你只有在绝对必要的时候才应该引用或解引用对象。在使用选择器时,Go会根据需要进行引用或解引用,并且方法将以正确的接收器类型调用。如果你以其他方式编写代码,只会让人们阅读你的代码时感到困惑。
英文:
No, you should only reference or dereference the object when absolutely necessary. Go does this as needed when using selectors, and the method will be called with the proper receiver type regardless. If you write it otherwise, you're just going to confuse people trying to read your code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论