英文:
What is the difference between a method receiver and parameter?
问题
看着下面显示的Go文档,我对接收器(receivers)和参数(parameters)之间的区别感到困惑:
func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
这个方法的签名如下:
这是一个名为save的方法,它以接收器p(指向Page的指针)作为参数。它不接受任何参数,并返回一个类型为error的值。
英文:
Looking at the Go documentation shown below, I'm having trouble understanding the distinction between receivers and parameters:
func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
>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.
答案1
得分: 11
接收器在C#中类似于this
:在x.f(a, b, c)
中,接收器是x
,参数是a
、b
和c
。当函数执行时,参数引用的是参数的副本。接收器和参数之间的重要区别在于,当接收器是接口类型时,在调用点确定要调用的函数是动态的,而不是静态的。
英文:
The receiver is like this
in C#: in x.f(a, b, c)
the receiver is x
and the arguments are a
, b
and c
. When the function is executed the parameters refer to copies of the arguments. The important difference between the receiver and parameters is that when the receiver is an interface type at the call site, the function to be called is determined dynamically rather than statically.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论