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

Go中的函數

在Go中,無論是方法還是函數都可以把他作為一個普通的函數來調用

Demo:

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這一項取消

mWcE34.png

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM