Golang中函数结构体,将函数转换为接口

函数结构体,将函数转换为接口

定义一个函数类型 F,并且实现接口 A 的方法,然后在这个方法中调用自己。这是 Go 语言中将其他函数转换为接口 A 的常用技巧(参数返回值定义与 F 一致)

实现一个动态生成的“回调函数”,比如缓存中,当key不存在,则需要从数据库或文件等远程数据源中取数据。所以回调函数不能写死。

采用用户自定义回调函数的方法,因此,在缓存的数据结构中,有一个成员方法变量为回调函数。

下面这段代码就是一个示例。

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)
}
//test
func TestGetterFunc_Get(t *testing.T) {
	var f Getter  = GetterFunc(func(key string) ([]byte,error) {
		return []byte(key),nil
	})

	expect := []byte("key")
	if v,_ := f.Get("key");!reflect.DeepEqual(v,expect){
		t.Error("callback failed")
	}
}

猜你喜欢

转载自www.cnblogs.com/Jun10ng/p/12616284.html
今日推荐