Goland技巧--接口型函数

126 阅读1分钟

Goland技巧--接口型函数

接口型函数的实现:

type Getter interface {
    Get(key string) ([]byte, error)
}
​
​
type GetterFunc func(key string) ([]byte, error)
​
​
func (f GetterFunc) Get(key string) ([]byte, error) {
    return f(key)
}

在这里,首先定义了一个接口类型Getter,只包含一个方法Get(key string) ([]byte, error)

紧接着定义了一个函数类型 GetterFunc,GetterFunc 参数和返回值与 Getter 中 Get 方法是一致的。

然后通过函数的特性,对函数类型 GetterFunc定义了Get方法,并在 Get 方法中调用自己,这样就实现了接口 Getter。

所以 GetterFunc 是一个实现了接口的函数类型,简称为接口型函数。


如果不提供这个把函数转换为接口的函数,你调用时就需要创建一个struct,然后实现对应的接口,创建一个实例作为参数,相比这种方式就麻烦得多了。