参数和接收器之间有什么区别?

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

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.

ex: http://play.golang.org/p/5n-N_Ov6Xz

huangapple
  • 本文由 发表于 2013年7月30日 03:37:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/17932722.html
匿名

发表评论

匿名网友

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

确定