英文:
What is the difference between parameter and receiver
问题
func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
英文:
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()
.
答案1
得分: 29
接收器只是参数的一种特殊情况。Go语言提供了一种语法糖,通过将第一个参数声明为接收器来将方法附加到类型上。
例如:
func (p *Page) save() error
读作“将一个名为save
的方法附加到类型*Page
上,并返回一个error
”,而不是声明:
func save(p *Page) error
这将读作“声明一个名为save
的函数,它接受一个类型为*Page
的参数,并返回一个error
”。
作为语法糖的证明,您可以尝试以下代码:
p := new(Page)
p.save()
(*Page).save(p)
最后两行表示完全相同的方法调用。
另外,请阅读这个答案。
英文:
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.
答案2
得分: 13
接收器是你声明方法的对象。
当想要向一个对象添加方法时,使用这种语法。
例如:http://play.golang.org/p/5n-N_Ov6Xz
英文:
The receiver is the object on what you declare your method.
When want to add a method to an object, you use this syntax.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论