gpt4 book ai didi

function - 类型如何间接引用其他函数基方法?

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

首先,我仍然不清楚如何提出这个问题,但我无法理解,有人可以帮助我理解这一点。如果我重命名“serveHTTP”或没有该方法,为什么下面的代码会出错。

prog.go:17: cannot use &status (type *statusHandler) as type http.Handler in argument to httptest.NewServer:
*statusHandler does not implement http.Handler (missing ServeHTTP method)
[process exited with non-zero status]

对于下面的代码

type statusHandler int

func (s *statusHandler) aServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println(" inside status handler serve http")
}

func main() {
status := statusHandler(400)
s := httptest.NewServer(&status)
log.Println("value of s is %d", s)
defer s.Close()
}

http://play.golang.org/p/QZIrWALAm_

最佳答案

ServeHTTP 需要满足 http.Handler界面。

type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}

Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here.

参见 Interfaces and Types in Effective Go了解更多信息。

关于function - 类型如何间接引用其他函数基方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27975648/

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