In golang method receiver is a pointer and not a pointer

  • 2020-06-07 04:38:52
  • OfStack

preface

The difference between receiver and non-pointer receiver ? Recently, when I was looking at the website, some students asked me the difference between receiver as pointer and not as pointer in golang. Here I explained the method in a simple and easy way to help the students who just learned golang. Let's start with a detailed introduction.

What is the method

In fact, as long as you understand the principle, you can basically understand the problem mentioned above.

The method is just a special function, and receiver is the first argument implicitly passed in.

For example


type test struct{
 name string
}

func (t test) TestValue() {
}

func (t *test) TestPointer() {
}

func main(){
 t := test{}
 
 m := test.TestValue
 m(t)
 
 m1 := (*test).TestPointer
 m1(&t) 
}

Is it easy to understand? Now let's add the code and see what's the difference between Pointers and non-pointers.


type test struct{
 name string
}

func (t test) TestValue() {
 fmt.Printf("%p\n", &t)
}

func (t *test) TestPointer() {
 fmt.Printf("%p\n", t)
}

func main(){
 t := test{}
 //0xc42000e2c0
 fmt.Printf("%p\n", &t)
 
 //0xc42000e2e0
 m := test.TestValue
 m(t)
 
 //0xc42000e2c0
 m1 := (*test).TestPointer
 m1(&t) 

}

I guess some of you already know that the value of the argument is copied when it is not a pointer, so every call is 1 TestValue() The value is replicated once.

What if it involves modifying the value?


type test struct{
 name string
}

func (t test) TestValue() {
 fmt.Printf("%s\n",t.name)
}

func (t *test) TestPointer() {
 fmt.Printf("%s\n",t.name)
}

func main(){
 t := test{"wang"}

 // There's a replication happening , Not affected by subsequent changes 
 m := t.TestValue
 
 t.name = "Li"
 m1 := (*test).TestPointer
 //Li
 m1(&t) 
 
 //wang
 m()
}

So you must pay attention to this kind of problem in programming.

So what is the relationship between these sets of methods? It borrows from qyuhen's reading notes in golang. It is also recommended for those who like golang to read this book, which is of great help to deepen their understanding of golang.

The & # 8226; Type T method set contains all receiver T methods.

The & # 8226; Type T method set contains all receiver T + T methods.

The & # 8226; If the type S contains the anonymous field T, the S method set contains the T method.

The & # 8226; If type S contains the anonymous field T, the S method set contains the T + T method.

The & # 8226; Whether T or T is embedded, the S method always contains T + *T method.

conclusion

Although golang is simple and easy to use, there are still many pits. The author has encountered many pits in the process of using golang, and I will bring them up gradually in the future.


Related articles: