声明Go服务器的ServeHTTP方法

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

Declaring ServeHTTP method of go server

问题

我正在按照这里的指南编写一个Go服务器:链接

我不理解下面的代码块:

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  //    ^^^^^ 这是什么意思?

它看起来不像是一个返回类型。在Go中,我理解返回类型应该跟在函数的参数后面。就像这个返回整数的函数:

func hello(s String) int {}

那么在ServeHTTP声明中的(*myHandler)是什么作用呢?

英文:

I'm following the guide to writing a Go server here.

I dont understand the following block:

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  //    ^^^^^ What does this do?

It doesnt look like a return type. In Go, my understanding is that return types follow the parameters of a function. Like this function that returns an integer:

func hello(s String) int {}

So what does the (*myHandler) in the ServeHTTP declaration do?

答案1

得分: 2

在下面的方法声明中:

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

myHandler 是该方法的接收器。这在 Go 的文档中有解释,关于方法定义

> 方法是带有_接收器_的函数。方法声明将标识符(方法名)绑定到方法,并将方法与接收器的基本类型关联起来。
>
> 接收器通过在方法名之前的额外参数部分指定。该参数部分必须声明一个非可变参数,即接收器。其类型必须是形式为 T 或 *T(可能使用括号)的类型,其中 T 是类型名称。T 所表示的类型称为接收器的基本类型;它不能是指针或接口类型,并且必须在与方法相同的包中声明。该方法被绑定到基本类型,并且方法名仅在类型 T 或 *T 的选择器中可见。

英文:

In the following method declaration

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

myHandler is the receiver of the method. This is explained in the Go documentation about method definition:

> A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver's base type.
>
> The receiver is specified via an extra parameter section preceding the method name. That parameter section must declare a single non-variadic parameter, the receiver. Its type must be of the form T or *T (possibly using parentheses) where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method. The method is said to be bound to the base type and the method name is visible only within selectors for type T or *T.

huangapple
  • 本文由 发表于 2016年3月28日 09:19:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/36254578.html
匿名

发表评论

匿名网友

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

确定