类型如何间接引用其他函数基方法?
How does a type indirectly refer to other functions base method?
首先,我还不清楚这个问题是如何提出来的,但我无法理解,有人可以帮助我理解这一点。如果我重命名 "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()
}
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。
首先,我还不清楚这个问题是如何提出来的,但我无法理解,有人可以帮助我理解这一点。如果我重命名 "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()
}
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。