This is a creation in Article, where the information may have evolved or changed.
Objective
Recently looked at the site has classmate question Golang method receiver for pointers and not for pointers what difference, here I use a simple and easy way to explain, help just learn Golang classmate.
What is the method?
In fact, as long as the understanding of this principle, the basic can understand the above mentioned problems.
method is actually a special function, receiver is the first argument implicitly passed in.
As an 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 to see what the difference is between a pointer and a non-pointer.
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) }
It is estimated that some students have understood that the value of the passed-in argument is copied when it is not a pointer. Therefore, the TestValue () value occurs once per call.
What if it involves modifying the value of the operation?
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()}
Therefore, the students in the programming encountered such problems must pay attention to.
What is the relationship between these sets of methods? Here borrowed Qyuhen in Golang reading notes, here also recommended like Golang friends to read this book, to deepen understanding Golang has a great help.
• The type T-set contains all receiver T methods.
• The type T-set contains all receiver T + t methods.
• If the type S contains an anonymous field T, the S-law set contains the T method.
• If the type S contains an anonymous field T, then the S-law set contains T + T method.
• The S-set always contains the T + *t method , regardless of theembedded T or T.
Conclusion
Golang Although easy to use, but still have a lot of pits. The author in the use of Golang process encountered a lot of pits, the back will be put forward in the blog, you are welcome to discuss together.