gpt4 book ai didi

go - 声明go服务器的ServeHTTP方法

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:18 24 4
gpt4 key购买 nike

我正在按照指南编写 Go 服务器 here .

我不明白下面的 block :

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

它看起来不像返回类型。在 Go 中,我的理解是返回类型遵循函数的参数。就像这个返回整数的函数:

func hello(s String) int {}

那么ServeHTTP声明中的(*myHandler)是做什么的呢?

最佳答案

在下面的方法声明中

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

myHandler 是方法的接收者。这在关于 method definition 的 Go 文档中有解释。 :

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.

关于go - 声明go服务器的ServeHTTP方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36254578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com