NOTE

4.2 接口型函数

1. 接口型函数是什么 一个实现了接口的函数类型,简称为接口型函数 2. 为什么需要接口型函数 既能够将普通的函数类型(需类型转换)作为参数,也可以将结构体作为参数,使用更为灵活,可读性也更好,这就是接口型函数的价值。 3. 实现 4. 参考 - Go 接口型函数的使用场景 \ 极客兔兔

Software Architecture & Engineering创建于 更新于 historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 接口型函数是什么

一个实现了接口的函数类型,简称为接口型函数

2. 为什么需要接口型函数

既能够将普通的函数类型(需类型转换)作为参数,也可以将结构体作为参数,使用更为灵活,可读性也更好,这就是接口型函数的价值。

3. 实现

//1.
// 定义了接口:Getter
// 通过key查询数据
type Getter interface {
	Get(key string) ([]byte, error)
}

//2.
// 定义了函数类型:GetterFunc
type GetterFunc func(key string) ([]byte, error)

// GetterFunc实现了Getter接口
func (f GetterFunc) Get(key string) ([]byte, error) {
	return f(key)
}

//3.
//从某数据源获取结果
//接口类型 Getter 是其中一个参数,代表某数据源
func GetFromSource(getter Getter, key string) []byte {
	buf, err := getter.Get(key)
	if err == nil {
		return buf
	}
	return nil
}

//4.
//从数据库获取数据
func getFromDB(key string) ([]byte, error) {
	return []byte(key), nil
}

//4.
//从Redis获取数据
//实现了Getter接口
type Redis struct {
}

func (r *Redis) Get(key string) ([]byte, error) {
	return []byte(key), nil
}
func TestIFunc(t *testing.T) {
	//GetFromSource的第一个参数既可以使用函数作为参数
	//这里GetterFunc(getFromDB)是强制类型转换
	GetFromSource(GetterFunc(getFromDB), "hello")
	//GetFromSource的第一个参数也可以使用结构体作为参数
	GetFromSource(new(Redis), "hello")

}

4. 参考