英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论