UNKO.fun

Blog Post

Golang当闭包实现interface

October 6, 2018 | 3 min

golang学习笔记

Post content

[学习笔记]Golang当闭包实现interface

下面直接看代码

/// 定义一个接口Test,
/// 包含方法Run
type Test interface {
    Run(cmd string) string
}

/// 定义一个类型TestFunc
/// 这个类型是一个func,并且接受一个string参数,返回一个string参数
type TestFunc func(cmd string) string

/// 类型TestFunc实现Test接口
/// 实现的内容为返回 执行TestFunc类型 得到的值
/// 类型TestFunc为一个方法,可以直接执行
func (t TestFunc)Run(cmd string) string {
    return t(cmd)
}

下面是使用方式

/// 声明变量t为TestFunc类型
/// TestFunc的括号内是该类型在该变量的具体的方法
t := TestFunc(func(cmd string) string {
    return cmd
})

/// 执行t.Run
/// 因为TestFunc实现了Test接口,所以可以调用
/// 根据Run的实现,会直接调用变量t的声明的方法
fmt.Println(t.Run("hello"))

这样实现,可以让具体的实现等到调用时才决定,增加灵活性。