参数和接收器有什么区别
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"
return ioutil.WriteFile(filename, p.Body, 0600)
}
The docs explain this as follows:
This method's signature reads: "This is a method named save that takes as its receiver p, a pointer to Page . It takes no parameters, and returns a value of type error."
I cant understand what the receiver is. I would read this as it being a parameter but then I would expect a parameter to be in save()
.
我正在关注Go教程,由于无法理解特定的方法签名而被困住: p>
func(p * Page)save()错误{
filename:= p.Title +“ .txt”
return ioutil.WriteFile(filename,p.Body,0600)
}
code> pre>
文档对此进行了如下解释: p>
此方法的签名为:“这是一个方法 命名为save的接收者p是指向Page的指针。它不带参数,并且返回错误类型的值。“ p>
blockquote>
我不明白 接收者是。 我将其作为参数读取,但随后我希望参数位于 save() code>中。 p>
div>
The receiver is the object on what you declare your method.
When want to add a method to an object, you use this syntax.
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.