去,为什么不应该使用“ this”作为方法接收者的名字[重复]
This question already has an answer here:
I use VS Code Go extension.
Here's my code
func (this *MyClass) Xxx() error {}
And It's mention me this
exported method
MyClass.Xxx
should have comment or be unexportedreceiver name should be a reflection of its identity; don't use generic names such as "
me
", "this
", or "self
";
</div>
此问题已经存在 在这里有一个答案: p>
-
在Go中是将接收方变量命名为“ self”具有误导性或良好做法吗?
5个答案
span>
li>
ul>
div>
I 使用VS Code Go扩展名。 p>
这是我的代码 p>
func(此* MyClass)Xxx()错误{} code> pre>
并且提到我这个 p>
导出的方法
MyClass.Xxx code>应该有注释或 不导出 p>
接收者名称应反映其身份; 不要使用通用名称,例如“
me code>”,“
this code>”或“
self code>”; p> blockquote> div>
v.Method()
is actually syntactic sugar and Go also understands the de-sugared version of it:(T).Method(v)
. You can see an example here.
package main
type T struct{}
func (t T) Method() {}
func main() {
t := T{}
t.Method() // this is valid
(T).Method(t) // this too
}
Naming the receiver like any other parameter reflects that it is, in fact, just another parameter quite well.
As Ixrec puts it in this answer:
In other languages the
this
/self
/whatever
variable typically has some special properties such as being magically provided by the language, or having special access to private methods (remember Go doesn't have private fields/methods).
Though the "receiver" is still being "magically provided" to some extent, it's so similar to a regular function argument it arguably doesn't count.