douren7921 2015-01-16 00:48
浏览 6
已采纳

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

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条回答 默认 最新

  • dongma7725 2015-01-16 00:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler