来自公众号:新世界杂货铺
前言
在日常的开发中我们除了定义函数以外, 我们还会定义一些方法。这本来没有什么, 但是一些从PHP或者其他面向对象语言转GO的同学往往会把receiver name命名为this
, self
, me
等。
笔者在实际项目开发中也遇到类似的同学, 屡次提醒却没有效果,于是决心写下这篇文章以便好好说服这些同学。
CR标准做法
首先我们来看一下GO推荐的标准命名Receiver Names
,以下内容摘抄自https://github.com/golang/go/wiki/CodeReviewComments#receiver-names:
The name of a method's receiver should be a reflection of its identity;
often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client").
Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that gives the method a special meaning.
In Go, the receiver of a method is just another parameter and therefore, should be named accordingly.
...
简单翻译总结有如下2点:
- 方法接受者名称应反映其身份, 并且不要使用
me
,this
,self
这些面向对象语言的典型标志符。 - 在go中方法接受者其实就是方法的另一个参数。
Receiver是方法的第一个参数!
上面的第二点, 可能不是很好理解,所以我们直接看下面的demo:
// T ...
type T int
// Println ...
func (t T) Println() {
fmt.Println("value: %v"