Explain the syntax for function declaration

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

Explain the syntax for function declaration

问题

请解释一下下面的语法,我在godoc中找到了下面的片段。我理解Cookie是函数名,name是它的参数,返回类型是(*Cookie, error),我不明白的部分是(r *Request),这部分具体表示什么意思。顺便说一下,我来自面向对象编程的背景。

func (r *Request) Cookie(name string) (*Cookie, error)

这段代码是一个方法的定义,其中:

  • func 表示这是一个函数或方法。
  • (r *Request) 是方法的接收者,表示该方法属于 Request 类型的对象。r 是接收者的名称,*Request 表示接收者的类型。
  • Cookie 是方法的名称。
  • (name string) 是方法的参数列表,其中 name 是参数的名称,string 是参数的类型。
  • (*Cookie, error) 是方法的返回类型,表示返回一个指向 Cookie 类型对象的指针和一个 error 类型的值。

所以,这个方法的作用是在 Request 对象中查找指定名称的 Cookie,并返回一个指向 Cookie 对象的指针和一个可能的错误。

英文:

Please explain the below syntax, I found this below snippet from godoc. I understand Cookie is function name and name is its argument and return type are (*Cookie, error), the part I could not understand is (r *Request), What exactly this part signifies. By the way I am from OOP background.

func (r *Request) Cookie(name string) (*Cookie, error)

答案1

得分: 2

这被称为接收器。

基本上,如果一个函数在其名称之前有一些内容(即接收器),那么它现在被称为方法。这是一种将结构体作为参数传递的好方法。

我建议你查看https://tour.golang.org/methods/1以获取更多信息。

https://gobyexample.com/methods 也很不错。

英文:

It is called a receiver.

Basically if a function has something before it's name (the receiver) it is now called a method. It's a good way to take structs as arguments.

I would recommend going over https://tour.golang.org/methods/1 for more information.

https://gobyexample.com/methods is also sweet

huangapple
  • 本文由 发表于 2016年12月29日 00:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/41366020.html
匿名

发表评论

匿名网友

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

确定