参数和接收器有什么区别 [英] What is the 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.它不带参数,并且返回错误类型的值."
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屋!