function type 可以理解為一組擁有相同參數(shù)類型和結(jié)果類型的方法的集合。我看也有人管他叫接口型函數(shù)逗噩。
A function type denotes the set of all functions with the same parameter and result types. The value of an uninitialized variable of function type is
nil
.
Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.
下面是function type最一般的打開方式
type Handler func(string) string
func process1(h Handler, s string) string {
return "process1" + h(s)
}
func process2(h Handler, s string) string {
return "process2" + h(s)
}
我們頂一個一個Handler瘪校,輸入?yún)?shù)為string车伞,輸出為string崎溃,且有一系列的復雜方法都以Handler作為輸入?yún)?shù)侦厚,做一些處理哑梳。這種情況下劲阎,我們可以很方便的去復用process1和process2方法。
processResult := process1(func(s string) string {
return strings.ToLower(s)
}, "gch")
process1的第一個參數(shù)為Handler鸠真,我們只需要構(gòu)建一個和它擁有同樣參數(shù)以及返回類型的方法即可悯仙。
接下來是一種更神奇的用法,我們知道吠卷,方法可以被聲明到任意類型(只要不是一個指針或者一個interface)锡垄,因此,我們可以給function type添加一個方法祭隔。
// 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)
}
這個例子來源于net/http
包货岭,我們只需要定義一個方法,擁有相同的參數(shù),如
func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
就能將這個方法轉(zhuǎn)型為HandlerFunc千贯,并調(diào)用ServerHTTP方法屯仗。
個人覺得這種給function附帶一個function的方法可讀性不太強,第一次看到會覺得很奇怪搔谴,更常見的用法是使用struct和interface組合起來使用魁袜,能以差不多的行的代碼實現(xiàn)相同的功能。
type HandleS struct {
handle func(w http.ResponseWriter, r *http.Request)
}
func NewHandler(f func(w http.ResponseWriter, r *http.Request)) Handlers {
return &HandlerS{handle: f}
}
func (h *HandlerS) ServerHTTP(w http.ResponseWriter, r *http.Request) {
h.Handle(w, r)
}
也許道行不深敦第,以后會有新的想法峰弹。