What is the difference between parameter and receiver

前端 未结 2 1020
南方客
南方客 2020-12-16 12:56

I am following a Go tutorial and am stuck as I cant understand a particular method signature:

func (p *Page) save() error {
    filename := p.Title + \".txt\         


        
相关标签:
2条回答
  • 2020-12-16 13:35

    The receiver is just a special case of a 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 that returns an error to the type *Page", as opposed to declaring:

    func save(p *Page) error
    

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

    As proof that it's only syntactic sugar you can try out the following code:

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

    Both last lines represent exactly the same method call.

    Also, read this answer.

    0 讨论(0)
  • 2020-12-16 13:42

    The receiver is the object on what you declare your method.

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

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

    0 讨论(0)
提交回复
热议问题