zoukankan      html  css  js  c++  java
  • 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")
    	}
    }
    
    
  • 相关阅读:
    nth_element 使用方法
    Codeforces-1326E Bombs
    GDB下调试查看数组部分内容
    0930,主外键设置
    0928,数据库
    0924,函数返回多个值
    0921,函数 枚举
    0920,结构体
    0918,练习题
    0916,双色球练习题
  • 原文地址:https://www.cnblogs.com/Jun10ng/p/12616284.html
Copyright © 2011-2022 走看看