我想知道這里發生了什么。有一個http處理程序的接口:type Handler interface { ServeHTTP(*Conn, *Request)}我想我了解這種實現。type Counter intfunc (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) { fmt.Fprintf(c, "counter = %d\n", ctr); ctr++;}根據我的理解,“ Counter”類型實現了接口,因為它具有一種具有所需簽名的方法。到現在為止還挺好。然后給出這個例子:func notFound(c *Conn, req *Request) { c.SetHeader("Content-Type", "text/plain;", "charset=utf-8"); c.WriteHeader(StatusNotFound); c.WriteString("404 page not found\n");}// Now we define a type to implement ServeHTTP:type HandlerFunc func(*Conn, *Request)func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) { f(c, req) // the receiver's a func; call it}// Convert function to attach method, implement the interface:var Handle404 = HandlerFunc(notFound);有人可以詳細說明為什么這些功能或如何將它們組合在一起嗎?
2 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
您對下半部分到底了解什么?這與上面的模式相同。他們沒有定義Counter類型為int,而是定義了一個稱為notFound的函數。然后,他們創建一種稱為HandlerFunc的函數類型,該函數帶有兩個參數,即連接和請求。然后,他們創建一個稱為ServeHTTP的新方法,該方法綁定到HandlerFunc類型。Handle404只是使用notFound函數的此類的一個實例。
- 2 回答
- 0 關注
- 270 瀏覽
添加回答
舉報
0/150
提交
取消