Open wisecsj opened 5 years ago
这个技巧在golang源码 net/http/server.go 也用到了
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
这样的话,任何一个具有func(ResponseWriter, *Request)
签名的函数通过类型转换为HandlerFunc即可自动实现Handler
接口
假设我们定义了一个接口,譬如:fmt.Stringer
我们可以定义函数类型,让相同签名的函数自动实现某个接口