当前位置: 动力学知识库 > 问答 > 编程问答 >

Declaring ServeHTTP method of go server

问题描述:

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?

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: