Why is it not recommended to use this or self for receiver name in go?

Release: 2023-07-21 13:23:26
forward
676 people have browsed it

In daily development, in addition to defining functions, we also define some methods. This is nothing, but some students who switch from PHP or other object-oriented languages ​​​​to GO often name the receiver name as this, self, me, etc.

The author also encountered similar students in actual project development. Repeated reminders had no effect, so I decided to write this article to persuade these students.

CR Standard Practice

First let’s take a look at the standard naming recommended by GOReceiver Names. The following content is excerpted from 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.
...
Copy after login

The simple translation summary has the following 2 points:

  1. The method receiver name should reflect its identity, and do not use me, this, self are typical identifiers of object-oriented languages.

  2. In go, the method receiver is actually another parameter of the method.

Receiver is the first parameter of the method!

The second point above may not be easy to understand, so let’s look at the demo below:

// T ...
type T int

// Println ...
func (t T) Println() {
	fmt.Println("value: %v", t)
}

func main() {
	t := T(1)
	t.Println()

	T.Println(t)
// receiver作为函数的第一个参数,这个时候发生值拷贝,所以方法内部的t变量是真实t变量的一个拷贝
// 这和this的含义是不相符的

}
// output:
value: 1
value: 1
Copy after login

通过上面的demo, 我们知道接受者可以直接作为第一个参数传递给方法的。而t.Println()应该就是Go中的一种语法糖了。

到这里可能有同学又要问了, 既然Go提供了这种语法糖,那我们这样命名有什么问题呢?笔者先不着急解释, 我们继续看下面的demo:

// Test ...
type Test struct {
	A int
}

// SetA ...
func (t Test) SetA(a int) {
	t.A = a
}

// SetA1 ...
func (t *Test) SetA1(a int) {
	t.A = a
}

func main() {
	t := Test{
		A: 3,
	}
	fmt.Println("demo1:")
	fmt.Println(t.A)
	t.SetA(5)
	fmt.Println(t.A)
	t1 := Test{
		A: 4,
	}
	fmt.Println("demo2:")
	fmt.Println(t1.A)
	(&t1).SetA1(6)
	fmt.Println(t1.A)
}
// output:
demo1:
3
3
demo2:
4
6
Copy after login

看上面的demo我们知道, 当receiver不是指针时调用SetA其值根本没有改变。

因为Go中都是值传递,所以你如果对SetA的receiver的名称命名为this, self等,它就已经失去了本身的意义——“调用一个对象的方法就是向该对象传递一条消息”。而且对象本身的属性也并不一定会发生改变。

综上: 请各位读者在对receiver命名时不要再用this, self等具有特殊含义的名称啦。

Receiver是可以为nil的!!!

最近在研读h2_bundle.go的时候,发现了一段特殊的代码,顿时惊出一身冷汗,姑在本文补充一下,以防止自己和各位读者踩坑。

源代码截图如下: Why is it not recommended to use this or self for receiver name in go?

惊出我一身冷汗的正是图中标红的部分,receiver居然还要判断为nil!在我的潜意识里一直是这样认为的,receiver默认都是有值的,直接使用就行了。这简直颠覆我的认知,吓得我赶紧写了个demo验证一下:

type A struct {
	v int
}

func (a *A) test() {
	fmt.Println(a == nil)
}

func (a *A) testV() {
	fmt.Println(a.v)
}


func main() {
var a *A
	a.test()
	a.testV()
}
Copy after login

上述输出如下:

Why is it not recommended to use this or self for receiver name in go?

a.test() can output normally, but panic is reported only when processing the internal variable v of the variable structure! ! ! Fortunately, this article has already introduced Receiver is the first parameter of the method. Because it is the first parameter, even if it is passed as a parameter, the function can be called normally even if it is nil, and panic will be reported where it is actually used.

The above is the detailed content of Why is it not recommended to use this or self for receiver name in go?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
go
source:Go语言进阶学习
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!