Go - difference between parameter and receiver

I follow the Go tutorial and am stuck as I cannot understand the specific method signature:

func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } 

The docs explain this as follows:

This method signature reads: "This is a method called save that takes p as the recipient, a pointer to the page. It takes no parameters and returns a type error value."

I canโ€™t understand what the receiver is. I would read this as a parameter, but then I expected the parameter to be in save() .

+4
source share
2 answers

A receiver is an object on which you declare your method.

When you want to add a method to an object, you use this syntax.

ex: http://play.golang.org/p/5n-N_Ov6Xz

+3
source

The receiver is only a special case of the parameter. Go provides syntactic sugar to attach methods to types by declaring the first parameter as a receiver.

For instance:

 func (p *Page) save() error 

reads "attach a method called save , which returns error in type *Page ", and does not declare:

 func save(p *Page) error 

which will read "declare a function called save that takes one parameter of type *Page and returns error "

As proof that this is only syntactic sugar, you can try the following code:

 p := new(Page) p.save() (*Page).save(p) 

Both last lines represent exactly the same method call.

Also read this answer .

+3
source

Source: https://habr.com/ru/post/1494129/


All Articles