Function typesin Go can also have methods. It’s hard to see, at first, why this would beuseful.
go 的Function types也可以拥有methods。它让人费解,首先这有什么用途。
There are two side effects to the fact thatfunction types can have methods in Go:
go的functions types拥有methods有个作用:
firstly, since any type that can have methodscan satisfy an interface, function types in Go can also be boxed into validinterface types.
第一:任何type都可以具有methods来满足某个interface. go的functions types 也能能够装箱进一个可用的interface类型中。
Secondly, sincemethods in Go can have either pointer or value receivers, we can use methods onfunction pointers to switch the function being pointed to in the method’s callingcontext.
第二.go类型中的methods可以是pointer作为接收者也可以是value类型作为接收者;我们可以使用receiver 为functionpointers的methods 来切换函数的指向在该metho的调用过程中。
That’s a bitheady at first, so let’s go through those two things in order.
这听起来让人兴奋,来让我们逐步了解这两见事情。
First, the mostobvious way to make a function type also satisfy an interface is to pick aninterface with only one method. Keeping it simple, let’s define an add function like wedid above, but we’ll give it an Error() stringmethod. In Go,any type that has an Error() stringmethod is avalid error type, so our function can serve as both a function and an error.
type binFunc func(int, int) int
func add(x, y int) int {
return x + y
}
func (f binFunc) Error() string {
return "binFunc error"
}
func main() {
var err error
err = binFunc(add)
fmt.Println(err)
}
函数签名和函数类型:
Ø 函数签名:输入和输入参数类型和顺序构成函数签名,与函数名无关;
Ø 定义函数类型时使用的是匿名函数模式:typeFuncType func(xxx)xxx,函数类型关注的是函数签名;
Ø 只要一个函数的函数签名和某个函数类型一致,该函数就可以强制转换为该函数类型的一个变量;
转换以后,就可以调用该函数类型的任何其他方法
You can run thistotally useless example on the Go Playground.
It’s worthnoting that in this case, we had to perform a type conversion to convert thefunction add, which is oftype func(int, int) int to type binFunc. This may seemlike an onerous(繁琐) misfeature(不好特性) of the Go runtime, but what if there was another valid conversion for func(int, int) int that wouldimplement error:
type loudBinFunc func(int, int) int
func (f loudBinFunc) Error() string {
return "THIS ERROR IS A LOT LOUDER"
}
If both binFunc and loudBinFunc are defined, theruntime wouldn’t know how to convert our add function. Evenif there is only one valid implementation of an interface for a given type, theruntime will not perform the conversion for us automatically. It seems veryannoying (恼人)at first, but it makes it easier towrite bug-free code.(健壮代码)
总结:手动强制转换是必须的,go是强类型语言,它保证代码的健壮性和无歧义
In the standardlibrary, we can see an example of using a function type to satisfy an interfacein the net/httppackage. The http.Handler type is the interface used by the standard library to register httphandlers:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
There’s also an http.HandlerFunc type, which is just a wrapper around func(http.ResponseWriter, *http.Request)that satisfies http.Handler. This allows us to use either a function or a struct as a web handler. The endresult is that we get both the http.Handle and http.HandleFuncfunctions, whichmakes it a bit more convenient to write web handlers.
Now that we’veestablished how methods on functions allow us to satisfy an interface, I’llshow a slightly more esoteric usage that turns out to be remarkably useful:let’s stick some functions in a json document.
现在我们实现了funcitons的methods怎么允许我们实现一个接口,我会略微介绍一个深奥的用法,该用法被证明非常有用。
The encoding/json package in the standardlibrary is the normal way to encode and decode json documents. This package isinterface-based; it defines an interface,json.Unmarshaler, that is to beused in the unmarshaling of json documents:
type Unmarshaler interface {
UnmarshalJSON([]byte) error
}
That is, if youdefine this method, the encoding/jsonpackage will usethis method when unpacking json data; otherwise, it attempts to figure out whatto do on its own (and generally gets it correct). Let’s stick with the binFuncexample, but this time, we’ll stick some binary functions in a jsondocument. We’ll start with the tired old binFuncdefinition:
type binFunc func(int, int) int
Since functionsthemselves do not have any persistent data, we need somewhere to registernames. We can use a map[string]binFunc to store our functions with their associated names:
var fnRegistry = map[string]binFunc{
"add": func(x, y int) int { return x + y },
"sub": func(x, y int) int { return x - y },
"mul": func(x, y int) int { return x * y },
"div": func(x, y int) int { return x / y },
"mod": func(x, y int) int { return x % y },
}
n Go, if weattempt to retrieve a value from a map with a nonexistent key, the retrieval operation will return the zero value for the giventype (if you’re asking “but what if we legitimately put nil into that map?”then see here). For functiontypes, the zero value is always nil, so we can justtest against nil to see if we’ve retrieved a value. Now we need to actuallyimplement the UnmarshalJSONmethod on our binFunc type. Since wewant to make changes that are seen by the caller of the function, we want toimplement UnmarshalJSON with a pointer receiver, and since we know we want a string, we justpiggy-back of the existing string unmarshaling capabilities of the standardjson package.
func (fn *binFunc) UnmarshalJSON(b []byte) error {
// start by unmarshaling the name of the function that we want
var name string
if err := json.Unmarshal(b, &name); err != nil {
return err
}
// get the function out of our function registry
found := getBinFunc(name)
if found == nil {
// return a descriptive error if we can't find the function
return fmt.Errorf("unknown function in (*binFunc)UnmarshalJSON: %s", name)
}
// dereference the pointer receiver, so that the changes are visible to the caller
*fn = found
return nil
}
With thatdefined, we can now unmarshal a binFunc from a json document. See here for thefull, runnable examplethat unpacks just one function, and here’s an example of using this tounpack a list of functions. Of course, this is just the tip of the iceberg, butit shows what types of things can be done with this technique.
上文中完整源码:
package main
import (
"encoding/json"
"fmt"
"log"
)
var jsonDoc = []byte(`"add"`)
var registry = map[string]binFunc{
"add": func(x, y int) int { return x + y },
"sub": func(x, y int) int { return x - y },
"mul": func(x, y int) int { return x * y },
"div": func(x, y int) int { return x / y },
"mod": func(x, y int) int { return x % y },
}
type binFunc func(int, int) int
func (fn *binFunc) UnmarshalJSON(b []byte) error {
var name string
if err := json.Unmarshal(b, &name); err != nil {
return err
}
// get the function out of our function registry
found := registry[name]
if found == nil {
// return a descriptive error if we can't find the function
return fmt.Errorf("unknown function in (*binFunc)UnmarshalJSON: %s", name)
}
// dereference the pointer receiver, so that the changes are visible to the caller
*fn = found
return nil
}
func main() {
var fn binFunc
if err := json.Unmarshal(jsonDoc, &fn); err != nil {
log.Fatal(err)
}
x := fn(5, 12)
fmt.Println(x)
}
528




被折叠的 条评论
为什么被折叠?



