我想知道這裏發生了什麼。函數實現接口
有一個HTTP處理程序接口:
type Handler interface {
ServeHTTP(*Conn, *Request)
}
此實現,我想我明白了。
type Counter int
func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
fmt.Fprintf(c, "counter = %d\n", ctr);
ctr++;
}
從我的理解是,該類型的「計數器」實現該接口,因爲它具有所需簽名的方法。到現在爲止還挺好。然後給出這個例子:
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);
有人可以詳細說明爲什麼或這些不同的函數如何配合在一起?
好吧我想我現在明白了,絆倒我的東西是notFound到HandlerFunc的轉換。在重讀有效轉換的轉換部分之後,更清楚如何也可以將其應用於函數。 http://golang.org/doc/effective_go.html#conversions – mbarkhau 2009-11-21 15:40:57