wisecsj / wisecsj.github.io

Blog
Apache License 2.0
0 stars 0 forks source link

Golang:interface的一种使用技巧 #16

Open wisecsj opened 5 years ago

wisecsj commented 5 years ago

假设我们定义了一个接口,譬如:fmt.Stringer

我们可以定义函数类型,让相同签名的函数自动实现某个接口

type FuncString func() string

func (f FuncString) String() string {
    return f()
}

func main() {
    var t fmt.Stringer = FuncString(func() string{
        return "hello,world"
    })

    fmt.Println(t)
}
wisecsj commented 5 years ago

这个技巧在golang源码 net/http/server.go 也用到了

wisecsj commented 5 years ago
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接口