Pointers 在Go中使用自定义http.Handler时为什么要使用指针?

Pointers 在Go中使用自定义http.Handler时为什么要使用指针?,pointers,go,methods,interface,Pointers,Go,Methods,Interface,在下面的代码段中调用http.Handle()时,我使用自己的templateHandler类型来实现http.Handler接口 主程序包 进口( “html/模板” “日志” “net/http” “路径/文件路径” “同步” ) 类型templateHandler结构{ 一次同步,一次 文件名字符串 temp*template.template } func(t*templateHandler)ServeHTTP(w http.ResponseWriter,r*http.Request){

在下面的代码段中调用
http.Handle()
时,我使用自己的
templateHandler
类型来实现
http.Handler
接口

主程序包
进口(
“html/模板”
“日志”
“net/http”
“路径/文件路径”
“同步”
)
类型templateHandler结构{
一次同步,一次
文件名字符串
temp*template.template
}
func(t*templateHandler)ServeHTTP(w http.ResponseWriter,r*http.Request){
t、 once.Do(func(){
t、 templ=template.Must(template.ParseFiles(filepath.Join(“templates”,t.filename)))
})
t、 执行模板(w,无)
}
func main(){
http.Handle(“/”,&templateHandler{filename:“chat.html”})
如果err:=http.ListenAndServe(“:8080”,nil);err!=nil{
log.Fatal(“ListendServe:,错误)
}
}
现在由于某种原因,我必须使用
&templateHandler{filename:“chat.html”}
传递一个指向
http.Handle()
的指针。如果没有
&
,我会出现以下错误:

cannot use (templateHandler literal) (value of type templateHandler) 
as http.Handler value in argument to http.Handle: 
missing method ServeHTTP
这到底是为什么?在这种情况下使用指针有什么区别?

需要一个实现的值(任何值),这意味着它必须有一个
ServeHTTP()
方法

您为
templateHandler.ServeHTTP()
方法使用了指针接收器,这意味着只有指向
templateHandler
的指针值具有此方法,而非指针
templateHandler
类型的指针值具有此方法

类型可能有与其关联的方法集。方法集是它的接口。任何其他类型
T
的方法集都由使用接收方类型
T
声明的所有方法组成。相应的
*T
的方法集是与接收方
*T
T
声明的所有方法集(也就是说,它还包含
T
的方法集)

非指针类型只有具有非指针接收器的方法。指针类型具有同时具有指针和非指针接收器的方法

您的
ServeHTTP()
方法修改接收器,因此它必须是指针。但如果其他处理程序不需要,则可以使用非指针接收器创建
ServeHTTP()
方法,在这种情况下,您可以使用非指针值作为
http.handler
,如本例所示:

type myhandler struct{}

func (m myhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}

func main() {
    // non-pointer struct value implements http.Handler:
    http.Handle("/", myhandler{})
}