去 - 参数和接收器之间的区别 [英] Go - difference between parameter and receiver
问题描述
我正在关注Go教程,因为我无法理解特定的方法签名而陷入困境:
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:
这个方法的签名是:这是一个名为save的方法,它作为接收者p,一个指向Page的指针,它不接受任何参数,并返回一个类型为error的值。
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."
我无法理解接收器是什么。我会读它作为一个参数,但我希望参数在 save()
。
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()
.
推荐答案
接收者是您声明方法的对象。
The receiver is the object on what you declare your method.
当您想要将方法添加到对象时,可以使用这个语法。
When want to add a method to an object, you use this syntax.
例如: http:/ /play.golang.org/p/5n-N_Ov6Xz
这篇关于去 - 参数和接收器之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!