In the Go language is to define the functions, methods and functions of the recipient're just one argument, and that is the way in func
and one more argument between identifiers. Defined between the recipient and the name of the function func keyword:
type Person struct { name string age int } func (p Person) say() { fmt.Printf("I'm %s,%d years old\n",p.name,p.age) }
The recipient has two, one is the value of the receiver a pointer to a recipient. As the name suggests, the value of the recipient, the recipient is the type of a value, is a copy of the internal method does not make changes to its real recipient; pointer recipient, type the recipient is a pointer, a reference to the recipient of this effect modification between the real recipient of reference.
Look at the two pieces of code
Code One:
package main import "fmt" type Person struct { name string age int } func (p Person) say() { fmt.Printf("I'm %s,%d years old\n",p.name,p.age) } func (p Person) older(){ p.age = p.age +1 } func main() { var p1 Person = Person{"zhansan",16} p1.older() p1.say() //output: I'm zhangsan,16 years old var p2 *Person = &Person{"lisi",17} p2.older() p2.say() //output: I'm lisi,17 years old }
Output:
#gosetup I'm zhansan,16 years old I'm lisi,17 years old
Code II:
package main import "fmt" type Person struct { name string age int } func (p Person) say() { fmt.Printf("I'm %s,%d years old\n",p.name,p.age) } func (p *Person) older(){ p.age = p.age +1 } func main() { var p1 Person = Person{"zhansan",16} p1.older() p1.say() //output: I'm zhangsan,17 years old var p2 *Person = &Person{"lisi",17} p2.older() p2.say() //output: I'm lisi,18 years old }
Output:
#gosetup I'm zhansan,17 years old I'm lisi,18 years old
This difference is only two codes in older () method which, first code value is the recipient method, the second segment of code is a pointer to the recipient methods.