What is the method
In fact As long as you understand this principle, you can basically understand the problems mentioned above.
The method is actually a special function, and the receiver is the first actual parameter passed in implicitly.Give me an exampletype 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 code to see what the difference is 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 Students have already understood that when the actual parameter is passed in when it is not a pointer, the value is copied. Therefore, every time TestValue() is called, the value is copied.
So what will be the result if the operation of modifying the value is involved?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"} //这里发生了复制,不受后面修改的影响 m := t.TestValue t.name = "Li" m1 := (*test).TestPointer //Li m1(&t) //wang m() }So all students must pay attention when encountering such problems in programming.
So what is the relationship between these method sets? Here I borrowed qyuhen’s study notes in golang, which is also recommended here. Friends who like golang should read this book, which will be of great help in deepening their understanding of golang.
• Type T method set contains all receiver T methods.
• The type
T methods.• If type S contains anonymous field T, then S method set contains T method.
Although golang is simple and easy to use, it still has many pitfalls. The author encountered many pitfalls in the process of using golang. I will mention them in the blog later. Everyone is welcome. discuss together.
• If type S contains anonymous field T, then S's method set contains T T methods.
• Regardless of embedding T or
T, the set of S methods always contains T *T methods.
Conclusion