方法接收器(method receiver)和参数(parameter)之间的区别是什么?

huangapple go评论76阅读模式
英文:

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,参数是abc。当函数执行时,参数引用的是参数的副本。接收器和参数之间的重要区别在于,当接收器是接口类型时,在调用点确定要调用的函数是动态的,而不是静态的。

英文:

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.

huangapple
  • 本文由 发表于 2014年11月27日 05:47:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/27159457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定