Last updated on

Go 之 接口型函数

效果:利用 GetterFunc 把函数转成接口,来满足 Getter 的要求 优点:可传函数可传实现接口的结构体

// Interface-type functions
func Test1(t *testing.T) {
	A := func(getter func() string) string {
		return getter()
	}

	if A(func() string {
		return "A"
	}) != "A" {
		t.Fatal("failed")
	}
}

type Getter interface {
	Get() string
}

// A GetterFunc implements Getter with a function.
type GetterFunc func() string

// Get implements Getter interface function
func (f GetterFunc) Get() string {
	return f()
}

type B struct {
	Name string
}

func (b B) Get() string {
	return b.Name
}

func Test2(t *testing.T) {

	A := func(getter Getter) string {
		return getter.Get()
	}

	if A(GetterFunc(func() string {
		return "A"
	})) != "A" {
		t.Fatal("failed")
	}

	b := B{
		Name: "B",
	}

	if A(b) != "B" {
		t.Fatal("failed")
	}
}

出自 动手写分布式缓存 - GeeCache 第二天 单机并发缓存

// A Getter loads data for a key.
type Getter interface {
	Get(key string) ([]byte, error)
}

// A GetterFunc implements Getter with a function.
type GetterFunc func(key string) ([]byte, error)

// Get implements Getter interface function
func (f GetterFunc) Get(key string) ([]byte, error) {
	return f(key)
}

文章参考 https://geektutu.com/post/7days-golang-q1.html