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

huangapple go评论93阅读模式
英文:

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()
}

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

答案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.

huangapple
  • 本文由 发表于 2015年1月16日 08:48:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/27975648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定