golang Receiver has generic name 问题解决

问题

Golang的方法接收者就是在函数名前的括号内的东西 如

func (self Car) run() // (self car)就是方法接收者

在JetBrains系类的开发工具中(IntelliJ、Goland)如果方法接收者名字是self me this类似的词,IDE会提示Receiver has generic name信息 如下图所示

mW6QpQ.png

解决

把 self me this类似的词 改掉,在Go中,无论是方法还是函数都可以把他作为一个普通的函数来调用

type Car struct {
    i int
}

func (c Car) run() {
    fmt.Println("my receiver is:", c.i)
}

func TestSelf(t *testing.T) {
    a := Car{1}
    a.run()
    Car.run(Car{22})
}

运行结果如下:

my receiver is: 1
my receiver is: 22

Go的方法只是语法糖而已,本质还是第一个参数是接收者的普通函数

解释

在其他面向对象的语言中this self me这些字段都有具体的含义,比如可以访问自己的私有方法或字段或者有其他特殊的含义。

但是在go中最好不用使用这些词,因为方法接收者只是一个普通的参数而,起不到这些词字面上的含义

go官方的代码规范也提到了这一点

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. The name need not be as descriptive as that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. Be consistent, too: if you call the receiver "c" in one method, don't call it "cl" in another.

如果想关闭掉这个提示可以在Setting->Editor->Inspections->Go->Code style issues 中把Receiver has generic name这一项取消

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值