调用指针上的方法的语法

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

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.

huangapple
  • 本文由 发表于 2014年3月14日 21:57:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/22407080.html
匿名

发表评论

匿名网友

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

确定