为什么go中的receiver name不推荐使用this或者self

来自公众号:新世界杂货铺

前言

在日常的开发中我们除了定义函数以外, 我们还会定义一些方法。这本来没有什么, 但是一些从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点:

  1. 方法接受者名称应反映其身份, 并且不要使用me, this, self这些面向对象语言的典型标志符。
  2. 在go中方法接受者其实就是方法的另一个参数。

Receiver是方法的第一个参数!

上面的第二点, 可能不是很好理解,所以我们直接看下面的demo:

// T ...
type T int

// Println ...
func (t T) Println() {
   
	fmt.Println("value: %v"
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值