英文:
How does a type indirectly refer to other functions base method?
问题
首先,我还不清楚如何构建这个问题,但我无法理解。有人可以帮助我理解吗?如果我重命名"serveHTTP"方法或者没有该方法,为什么下面的代码会出错。
对于下面的代码:
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()
}
错误信息如下:
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]
这是因为statusHandler
类型没有实现http.Handler
接口的ServeHTTP
方法。要解决这个问题,你需要将aServeHTTP
方法重命名为ServeHTTP
。
英文:
First of all, I am still not clear how to frame this question, but I am not able to understand, can someone help me in understanding this. Why does the below code errors out if I rename "serveHTTP" or not have that method.
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]
for the below code
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()
}
答案1
得分: 2
ServeHTTP
是必需的,以满足http.Handler
接口。
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
>在Go中,接口提供了一种指定对象行为的方式:如果某个对象可以执行这个操作,那么它可以在这里使用。
有关更多信息,请参阅Effective Go中的接口和类型。
英文:
ServeHTTP
is required to satisfy the http.Handler
interface.
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.
See Interfaces and Types in Effective Go for more info.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论